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