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