xref: /webtrees/app/Module/FanChartModule.php (revision 6930e9b42b9925bfc3a874fc2aaa59aabd0d2418)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 <https://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\I18N;
26use Fisharebest\Webtrees\Individual;
27use Fisharebest\Webtrees\Menu;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\Services\ChartService;
30use Fisharebest\Webtrees\Validator;
31use Fisharebest\Webtrees\Webtrees;
32use Psr\Http\Message\ResponseInterface;
33use Psr\Http\Message\ServerRequestInterface;
34use Psr\Http\Server\RequestHandlerInterface;
35
36use function app;
37use function array_filter;
38use function array_keys;
39use function array_map;
40use function assert;
41use function cos;
42use function deg2rad;
43use function e;
44use function gd_info;
45use function hexdec;
46use function imagecolorallocate;
47use function imagecolortransparent;
48use function imagecreate;
49use function imagedestroy;
50use function imagefilledarc;
51use function imagefilledrectangle;
52use function imagepng;
53use function imagettfbbox;
54use function imagettftext;
55use function implode;
56use function intdiv;
57use function max;
58use function mb_substr;
59use function min;
60use function ob_get_clean;
61use function ob_start;
62use function redirect;
63use function response;
64use function round;
65use function route;
66use function rtrim;
67use function sin;
68use function sqrt;
69use function strip_tags;
70use function substr;
71use function view;
72
73use const IMG_ARC_PIE;
74
75/**
76 * Class FanChartModule
77 */
78class FanChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
79{
80    use ModuleChartTrait;
81
82    protected const ROUTE_URL = '/tree/{tree}/fan-chart-{style}-{generations}-{width}/{xref}';
83
84    // Chart styles
85    private const STYLE_HALF_CIRCLE          = '2';
86    private const STYLE_THREE_QUARTER_CIRCLE = '3';
87    private const STYLE_FULL_CIRCLE          = '4';
88
89    // Defaults
90    private const   DEFAULT_STYLE       = self::STYLE_THREE_QUARTER_CIRCLE;
91    private const   DEFAULT_GENERATIONS = 4;
92    private const   DEFAULT_WIDTH       = 100;
93    protected const DEFAULT_PARAMETERS  = [
94        'style'       => self::DEFAULT_STYLE,
95        'generations' => self::DEFAULT_GENERATIONS,
96        'width'       => self::DEFAULT_WIDTH,
97    ];
98
99    // Limits
100    private const MINIMUM_GENERATIONS = 2;
101    private const MAXIMUM_GENERATIONS = 9;
102    private const MINIMUM_WIDTH       = 50;
103    private const MAXIMUM_WIDTH       = 500;
104
105    // Chart layout parameters
106    private const FONT               = Webtrees::ROOT_DIR . 'resources/fonts/DejaVuSans.ttf';
107    private const CHART_WIDTH_PIXELS = 800;
108    private const TEXT_SIZE_POINTS   = self::CHART_WIDTH_PIXELS / 120.0;
109    private const GAP_BETWEEN_RINGS  = 2;
110
111    private ChartService $chart_service;
112
113    /**
114     * FanChartModule constructor.
115     *
116     * @param ChartService $chart_service
117     */
118    public function __construct(ChartService $chart_service)
119    {
120        $this->chart_service = $chart_service;
121    }
122
123    /**
124     * Initialization.
125     *
126     * @return void
127     */
128    public function boot(): void
129    {
130        Registry::routeFactory()->routeMap()
131            ->get(static::class, static::ROUTE_URL, $this)
132            ->allows(RequestMethodInterface::METHOD_POST);
133    }
134
135    /**
136     * How should this module be identified in the control panel, etc.?
137     *
138     * @return string
139     */
140    public function title(): string
141    {
142        /* I18N: Name of a module/chart */
143        return I18N::translate('Fan chart');
144    }
145
146    /**
147     * A sentence describing what this module does.
148     *
149     * @return string
150     */
151    public function description(): string
152    {
153        /* I18N: Description of the “Fan Chart” module */
154        return I18N::translate('A fan chart of an individual’s ancestors.');
155    }
156
157    /**
158     * CSS class for the URL.
159     *
160     * @return string
161     */
162    public function chartMenuClass(): string
163    {
164        return 'menu-chart-fanchart';
165    }
166
167    /**
168     * Return a menu item for this chart - for use in individual boxes.
169     *
170     * @param Individual $individual
171     *
172     * @return Menu|null
173     */
174    public function chartBoxMenu(Individual $individual): ?Menu
175    {
176        return $this->chartMenu($individual);
177    }
178
179    /**
180     * The title for a specific instance of this chart.
181     *
182     * @param Individual $individual
183     *
184     * @return string
185     */
186    public function chartTitle(Individual $individual): string
187    {
188        /* I18N: https://en.wikipedia.org/wiki/Family_tree#Fan_chart - %s is an individual’s name */
189        return I18N::translate('Fan chart of %s', $individual->fullName());
190    }
191
192    /**
193     * A form to request the chart parameters.
194     *
195     * @param Individual                                $individual
196     * @param array<bool|int|string|array<string>|null> $parameters
197     *
198     * @return string
199     */
200    public function chartUrl(Individual $individual, array $parameters = []): string
201    {
202        return route(static::class, [
203                'xref' => $individual->xref(),
204                'tree' => $individual->tree()->name(),
205            ] + $parameters + self::DEFAULT_PARAMETERS);
206    }
207
208    /**
209     * @param ServerRequestInterface $request
210     *
211     * @return ResponseInterface
212     */
213    public function handle(ServerRequestInterface $request): ResponseInterface
214    {
215        $tree        = Validator::attributes($request)->tree();
216        $user        = Validator::attributes($request)->user();
217        $xref        = Validator::attributes($request)->isXref()->string('xref');
218        $style       = Validator::attributes($request)->isInArrayKeys($this->styles())->string('style');
219        $generations = Validator::attributes($request)->isBetween(self::MINIMUM_GENERATIONS, self::MAXIMUM_GENERATIONS)->integer('generations');
220        $width       = Validator::attributes($request)->isBetween(self::MINIMUM_WIDTH, self::MAXIMUM_WIDTH)->integer('width');
221        $ajax        = Validator::queryParams($request)->boolean('ajax', false);
222
223        // Convert POST requests into GET requests for pretty URLs.
224        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
225            return redirect(route(static::class, [
226                'tree'        => $tree->name(),
227                'generations' => Validator::parsedBody($request)->isBetween(self::MINIMUM_GENERATIONS, self::MAXIMUM_GENERATIONS)->integer('generations'),
228                'style'       => Validator::parsedBody($request)->isInArrayKeys($this->styles())->string('style'),
229                'width'       => Validator::parsedBody($request)->isBetween(self::MINIMUM_WIDTH, self::MAXIMUM_WIDTH)->integer('width'),
230                'xref'        => Validator::parsedBody($request)->isXref()->string('xref'),
231             ]));
232        }
233
234        Auth::checkComponentAccess($this, ModuleChartInterface::class, $tree, $user);
235
236        $individual  = Registry::individualFactory()->make($xref, $tree);
237        $individual  = Auth::checkIndividualAccess($individual, false, true);
238
239        if ($ajax) {
240            return $this->chart($individual, $style, $width, $generations);
241        }
242
243        $ajax_url = $this->chartUrl($individual, [
244            'ajax'        => true,
245            'generations' => $generations,
246            'style'       => $style,
247            'width'       => $width,
248        ]);
249
250        return $this->viewResponse('modules/fanchart/page', [
251            'ajax_url'            => $ajax_url,
252            'generations'         => $generations,
253            'individual'          => $individual,
254            'maximum_generations' => self::MAXIMUM_GENERATIONS,
255            'minimum_generations' => self::MINIMUM_GENERATIONS,
256            'maximum_width'       => self::MAXIMUM_WIDTH,
257            'minimum_width'       => self::MINIMUM_WIDTH,
258            'module'              => $this->name(),
259            'style'               => $style,
260            'styles'              => $this->styles(),
261            'title'               => $this->chartTitle($individual),
262            'tree'                => $tree,
263            'width'               => $width,
264        ]);
265    }
266
267    /**
268     * Generate both the HTML and PNG components of the fan chart
269     *
270     * @param Individual $individual
271     * @param string     $style
272     * @param int        $width
273     * @param int        $generations
274     *
275     * @return ResponseInterface
276     */
277    protected function chart(Individual $individual, string $style, int $width, int $generations): ResponseInterface
278    {
279        $ancestors = $this->chart_service->sosaStradonitzAncestors($individual, $generations);
280
281        $width = intdiv(self::CHART_WIDTH_PIXELS * $width, 100);
282
283        switch ($style) {
284            case self::STYLE_HALF_CIRCLE:
285                $chart_start_angle = 180;
286                $chart_end_angle   = 360;
287                $height            = intdiv($width, 2);
288                break;
289
290            case self::STYLE_THREE_QUARTER_CIRCLE:
291                $chart_start_angle = 135;
292                $chart_end_angle   = 405;
293                $height            = intdiv($width * 86, 100);
294                break;
295
296            case self::STYLE_FULL_CIRCLE:
297            default:
298                $chart_start_angle = 90;
299                $chart_end_angle   = 450;
300                $height            = $width;
301                break;
302        }
303
304        // Start with a transparent image.
305        $image       = imagecreate($width, $height);
306        $transparent = imagecolorallocate($image, 0, 0, 0);
307        imagecolortransparent($image, $transparent);
308        imagefilledrectangle($image, 0, 0, $width, $height, $transparent);
309
310        // Use theme-specified colors.
311        /** @var ModuleThemeInterface $theme */
312        $theme       = app(ModuleThemeInterface::class);
313        $text_color  = $this->imageColor($image, '000000');
314        $backgrounds = [
315            'M' => $this->imageColor($image, 'b1cff0'),
316            'F' => $this->imageColor($image, 'e9daf1'),
317            'U' => $this->imageColor($image, 'eeeeee'),
318        ];
319
320        // Co-ordinates are measured from the top-left corner.
321        $center_x  = intdiv($width, 2);
322        $center_y  = $center_x;
323        $arc_width = $width / $generations / 2.0;
324
325        // Popup menus for each ancestor.
326        $html = '';
327
328        // Areas for the image map.
329        $areas = '';
330
331        for ($generation = $generations; $generation >= 1; $generation--) {
332            // Which ancestors to include in this ring. 1, 2-3, 4-7, 8-15, 16-31, etc.
333            // The end of the range is also the number of ancestors in the ring.
334            $sosa_start = 2 ** $generation - 1;
335            $sosa_end   = 2 ** ($generation - 1);
336
337            $arc_diameter = intdiv($width * $generation, $generations);
338            $arc_radius = $arc_diameter / 2;
339
340            // Draw an empty background, for missing ancestors.
341            imagefilledarc(
342                $image,
343                $center_x,
344                $center_y,
345                $arc_diameter,
346                $arc_diameter,
347                $chart_start_angle,
348                $chart_end_angle,
349                $backgrounds['U'],
350                IMG_ARC_PIE
351            );
352
353            $arc_diameter -= 2 * self::GAP_BETWEEN_RINGS;
354
355            for ($sosa = $sosa_start; $sosa >= $sosa_end; $sosa--) {
356                if ($ancestors->has($sosa)) {
357                    $individual = $ancestors->get($sosa);
358
359                    $chart_angle = $chart_end_angle - $chart_start_angle;
360                    $start_angle = $chart_start_angle + intdiv($chart_angle * ($sosa - $sosa_end), $sosa_end);
361                    $end_angle   = $chart_start_angle + intdiv($chart_angle * ($sosa - $sosa_end + 1), $sosa_end);
362                    $angle       = $end_angle - $start_angle;
363
364                    imagefilledarc(
365                        $image,
366                        $center_x,
367                        $center_y,
368                        $arc_diameter,
369                        $arc_diameter,
370                        $start_angle,
371                        $end_angle,
372                        $backgrounds[$individual->sex()],
373                        IMG_ARC_PIE
374                    );
375
376                    // Text is written at a tangent to the arc.
377                    $text_angle = 270.0 - ($start_angle + $end_angle) / 2.0;
378
379                    $text_radius = $arc_diameter / 2.0 - $arc_width * 0.25;
380
381                    // Don't draw text right up to the edge of the arc.
382                    if ($angle === 360) {
383                        $delta = 90;
384                    } elseif ($angle === 180) {
385                        if ($generation === 1) {
386                            $delta = 20;
387                        } else {
388                            $delta = 60;
389                        }
390                    } elseif ($angle > 120) {
391                        $delta = 45;
392                    } elseif ($angle > 60) {
393                        $delta = 15;
394                    } else {
395                        $delta = 1;
396                    }
397
398                    $tx_start = $center_x + $text_radius * cos(deg2rad($start_angle + $delta));
399                    $ty_start = $center_y + $text_radius * sin(deg2rad($start_angle + $delta));
400                    $tx_end   = $center_x + $text_radius * cos(deg2rad($end_angle - $delta));
401                    $ty_end   = $center_y + $text_radius * sin(deg2rad($end_angle - $delta));
402
403                    $max_text_length = (int) sqrt(($tx_end - $tx_start) ** 2 + ($ty_end - $ty_start) ** 2);
404
405                    $text_lines = array_filter([
406                        I18N::reverseText($individual->fullName()),
407                        I18N::reverseText($individual->alternateName() ?? ''),
408                        I18N::reverseText($individual->lifespan()),
409                    ]);
410
411                    $text_lines = array_map(
412                        fn (string $line): string => $this->fitTextToPixelWidth($line, $max_text_length),
413                        $text_lines
414                    );
415
416                    $text = implode("\n", $text_lines);
417
418                    if ($generation === 1) {
419                        $ty_start -= $text_radius / 2;
420                    }
421
422                    // If PHP is compiled with --enable-gd-jis-conv, then the function
423                    // imagettftext() is modified to expect EUC-JP encoding instead of UTF-8.
424                    // Attempt to detect and convert...
425                    if (gd_info()['JIS-mapped Japanese Font Support'] ?? false) {
426                        $text = mb_convert_encoding($text, 'EUC-JP', 'UTF-8');
427                    }
428
429                    imagettftext(
430                        $image,
431                        self::TEXT_SIZE_POINTS,
432                        $text_angle,
433                        (int) $tx_start,
434                        (int) $ty_start,
435                        $text_color,
436                        static::FONT,
437                        $text
438                    );
439                    // Debug text positions by underlining first line of text
440                    //imageline($image, (int) $tx_start, (int) $ty_start, (int) $tx_end, (int) $ty_end, $backgrounds['U']);
441
442                    $areas .= '<area shape="poly" coords="';
443                    for ($deg = $start_angle; $deg <= $end_angle; $deg++) {
444                        $rad = deg2rad($deg);
445                        $areas .= round($center_x + $arc_radius * cos(deg2rad($rad)), 1) . ',';
446                        $areas .= round($center_y + $arc_radius * sin(deg2rad($rad)), 1) . ',';
447                    }
448                    for ($deg = $end_angle; $deg >= $start_angle; $deg--) {
449                        $rad = deg2rad($deg);
450                        $areas .= round($center_x + ($arc_radius - $arc_width) * cos($rad), 1) . ',';
451                        $areas .= round($center_y + ($arc_radius - $arc_width) * sin($rad), 1) . ',';
452                    }
453                    $rad = deg2rad($start_angle);
454                    $areas .= round($center_x + $arc_radius * cos($rad), 1) . ',';
455                    $areas .= round($center_y + $arc_radius * sin($rad), 1) . '"';
456
457                    $areas .= ' href="#' . e($individual->xref()) . '"';
458                    $areas .= ' alt="' . strip_tags($individual->fullName()) . '"';
459                    $areas .= ' title="' . strip_tags($individual->fullName()) . '">';
460
461                    $html  .= '<div id="' . $individual->xref() . '" class="fan_chart_menu">';
462                    $html  .= '<a href="' . e($individual->url()) . '" class="dropdown-item p-1">';
463                    $html  .= $individual->fullName();
464                    $html  .= '</a>';
465
466                    foreach ($theme->individualBoxMenu($individual) as $menu) {
467                        $link  = $menu->getLink();
468                        $class = $menu->getClass();
469                        $html .= '<a href="' . e($link) . '" class="dropdown-item p-1 ' . e($class) . '">';
470                        $html .= $menu->getLabel();
471                        $html .= '</a>';
472                    }
473
474                    $html .= '</div>';
475                }
476            }
477        }
478
479        ob_start();
480        imagepng($image);
481        imagedestroy($image);
482        $png = ob_get_clean();
483
484        return response(view('modules/fanchart/chart', [
485            'fanh'  => $height,
486            'fanw'  => $width,
487            'html'  => $html,
488            'areas' => $areas,
489            'png'   => $png,
490            'title' => $this->chartTitle($individual),
491        ]));
492    }
493
494    /**
495     * Convert a CSS color into a GD color.
496     *
497     * @param resource $image
498     * @param string   $css_color
499     *
500     * @return int
501     */
502    protected function imageColor($image, string $css_color): int
503    {
504        return imagecolorallocate(
505            $image,
506            (int) hexdec(substr($css_color, 0, 2)),
507            (int) hexdec(substr($css_color, 2, 2)),
508            (int) hexdec(substr($css_color, 4, 2))
509        );
510    }
511
512    /**
513     * This chart can display its output in a number of styles
514     *
515     * @return array<string>
516     */
517    protected function styles(): array
518    {
519        return [
520            /* I18N: layout option for the fan chart */
521            self::STYLE_HALF_CIRCLE          => I18N::translate('half circle'),
522            /* I18N: layout option for the fan chart */
523            self::STYLE_THREE_QUARTER_CIRCLE => I18N::translate('three-quarter circle'),
524            /* I18N: layout option for the fan chart */
525            self::STYLE_FULL_CIRCLE          => I18N::translate('full circle'),
526        ];
527    }
528
529    /**
530     * Fit text to a given number of pixels by either cropping to fit,
531     * or adding spaces to center.
532     *
533     * @param string $text
534     * @param int    $pixels
535     *
536     * @return string
537     */
538    protected function fitTextToPixelWidth(string $text, int $pixels): string
539    {
540        while ($this->textWidthInPixels($text) > $pixels) {
541            $text = mb_substr($text, 0, -1);
542        }
543
544        while ($this->textWidthInPixels(' ' . $text . ' ') < $pixels) {
545            $text = ' ' . $text . ' ';
546        }
547
548        // We only need the leading spaces.
549        return rtrim($text);
550    }
551
552    /**
553     * @param string $text
554     *
555     * @return int
556     */
557    protected function textWidthInPixels(string $text): int
558    {
559        $bounding_box = imagettfbbox(self::TEXT_SIZE_POINTS, 0, self::FONT, $text);
560
561        return $bounding_box[4] - $bounding_box[0];
562    }
563}
564