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