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