xref: /webtrees/app/Module/FanChartModule.php (revision 9e18e23b968678b192e5541acd3252e4978d69c3)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://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\Services\ChartService;
29use Fisharebest\Webtrees\Webtrees;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Server\RequestHandlerInterface;
33
34use function app;
35use function array_keys;
36use function assert;
37use function implode;
38use function max;
39use function min;
40use function redirect;
41use function route;
42
43/**
44 * Class FanChartModule
45 */
46class FanChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
47{
48    use ModuleChartTrait;
49
50    private const ROUTE_NAME = 'fan-chart';
51    private const ROUTE_URL  = '/tree/{tree}/fan-chart-{style}-{generations}-{width}/{xref}';
52
53    // Chart styles
54    private const STYLE_HALF_CIRCLE          = '2';
55    private const STYLE_THREE_QUARTER_CIRCLE = '3';
56    private const STYLE_FULL_CIRCLE          = '4';
57
58    // Defaults
59    private const   DEFAULT_STYLE       = self::STYLE_THREE_QUARTER_CIRCLE;
60    private const   DEFAULT_GENERATIONS = 4;
61    private const   DEFAULT_WIDTH       = 100;
62    protected const DEFAULT_PARAMETERS  = [
63        'style'       => self::DEFAULT_STYLE,
64        'generations' => self::DEFAULT_GENERATIONS,
65        'width'       => self::DEFAULT_WIDTH,
66    ];
67
68    // Limits
69    private const MINIMUM_GENERATIONS = 2;
70    private const MAXIMUM_GENERATIONS = 9;
71    private const MINIMUM_WIDTH       = 50;
72    private const MAXIMUM_WIDTH       = 500;
73
74    /** @var ChartService */
75    private $chart_service;
76
77    /**
78     * FanChartModule constructor.
79     *
80     * @param ChartService $chart_service
81     */
82    public function __construct(ChartService $chart_service)
83    {
84        $this->chart_service = $chart_service;
85    }
86
87    /**
88     * Initialization.
89     *
90     * @return void
91     */
92    public function boot(): void
93    {
94        $router_container = app(RouterContainer::class);
95        assert($router_container instanceof RouterContainer);
96
97        $router_container->getMap()
98            ->get(self::ROUTE_NAME, self::ROUTE_URL, self::class)
99            ->allows(RequestMethodInterface::METHOD_POST)
100            ->tokens([
101                'generations' => '\d+',
102                'style'       => implode('|', array_keys($this->styles())),
103                'width'       => '\d+',
104            ]);
105    }
106
107    /**
108     * How should this module be identified in the control panel, etc.?
109     *
110     * @return string
111     */
112    public function title(): string
113    {
114        /* I18N: Name of a module/chart */
115        return I18N::translate('Fan chart');
116    }
117
118    /**
119     * A sentence describing what this module does.
120     *
121     * @return string
122     */
123    public function description(): string
124    {
125        /* I18N: Description of the “Fan Chart” module */
126        return I18N::translate('A fan chart of an individual’s ancestors.');
127    }
128
129    /**
130     * CSS class for the URL.
131     *
132     * @return string
133     */
134    public function chartMenuClass(): string
135    {
136        return 'menu-chart-fanchart';
137    }
138
139    /**
140     * Return a menu item for this chart - for use in individual boxes.
141     *
142     * @param Individual $individual
143     *
144     * @return Menu|null
145     */
146    public function chartBoxMenu(Individual $individual): ?Menu
147    {
148        return $this->chartMenu($individual);
149    }
150
151    /**
152     * The title for a specific instance of this chart.
153     *
154     * @param Individual $individual
155     *
156     * @return string
157     */
158    public function chartTitle(Individual $individual): string
159    {
160        /* I18N: http://en.wikipedia.org/wiki/Family_tree#Fan_chart - %s is an individual’s name */
161        return I18N::translate('Fan chart of %s', $individual->fullName());
162    }
163
164    /**
165     * A form to request the chart parameters.
166     *
167     * @param Individual $individual
168     * @param mixed[]    $parameters
169     *
170     * @return string
171     */
172    public function chartUrl(Individual $individual, array $parameters = []): string
173    {
174        return route(self::ROUTE_NAME, [
175                'xref' => $individual->xref(),
176                'tree' => $individual->tree()->name(),
177            ] + $parameters + self::DEFAULT_PARAMETERS);
178    }
179
180    /**
181     * @param ServerRequestInterface $request
182     *
183     * @return ResponseInterface
184     */
185    public function handle(ServerRequestInterface $request): ResponseInterface
186    {
187        $tree        = $request->getAttribute('tree');
188        $user        = $request->getAttribute('user');
189        $xref        = $request->getAttribute('xref');
190        $style       = $request->getAttribute('style');
191        $generations = (int) $request->getAttribute('generations');
192        $width       = (int) $request->getAttribute('width');
193        $ajax        = $request->getQueryParams()['ajax'] ?? '';
194        $individual  = Individual::getInstance($xref, $tree);
195
196        // Convert POST requests into GET requests for pretty URLs.
197        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
198            return redirect(route(self::ROUTE_NAME, [
199                'tree'        => $request->getAttribute('tree')->name(),
200                'xref'        => $request->getParsedBody()['xref'],
201                'style'       => $request->getParsedBody()['style'],
202                'generations' => $request->getParsedBody()['generations'],
203                'width'       => $request->getParsedBody()['width'],
204            ]));
205        }
206
207        Auth::checkIndividualAccess($individual);
208        Auth::checkComponentAccess($this, 'chart', $tree, $user);
209
210        $width = min($width, self::MAXIMUM_WIDTH);
211        $width = max($width, self::MINIMUM_WIDTH);
212
213        $generations = min($generations, self::MAXIMUM_GENERATIONS);
214        $generations = max($generations, self::MINIMUM_GENERATIONS);
215
216        if ($ajax === '1') {
217            return $this->chart($individual, $style, $width, $generations);
218        }
219
220        $ajax_url = $this->chartUrl($individual, [
221            'ajax'        => true,
222            'generations' => $generations,
223            'style'       => $style,
224            'width'       => $width,
225        ]);
226
227        return $this->viewResponse('modules/fanchart/page', [
228            'ajax_url'            => $ajax_url,
229            'generations'         => $generations,
230            'individual'          => $individual,
231            'maximum_generations' => self::MAXIMUM_GENERATIONS,
232            'minimum_generations' => self::MINIMUM_GENERATIONS,
233            'maximum_width'       => self::MAXIMUM_WIDTH,
234            'minimum_width'       => self::MINIMUM_WIDTH,
235            'module'              => $this->name(),
236            'style'               => $style,
237            'styles'              => $this->styles(),
238            'title'               => $this->chartTitle($individual),
239            'width'               => $width,
240        ]);
241    }
242
243    /**
244     * Generate both the HTML and PNG components of the fan chart
245     *
246     * @param Individual $individual
247     * @param string     $style
248     * @param int        $width
249     * @param int        $generations
250     *
251     * @return ResponseInterface
252     */
253    protected function chart(Individual $individual, string $style, int $width, int $generations): ResponseInterface
254    {
255        $ancestors = $this->chart_service->sosaStradonitzAncestors($individual, $generations);
256
257        $gen  = $generations - 1;
258        $sosa = 2 ** $generations - 1;
259
260        // fan size
261        $fanw = 640 * $width / 100;
262        $cx   = $fanw / 2 - 1; // center x
263        $cy   = $cx; // center y
264        $rx   = $fanw - 1;
265        $rw   = $fanw / ($gen + 1);
266        $fanh = $fanw; // fan height
267        if ($style === self::STYLE_HALF_CIRCLE) {
268            $fanh = $fanh * ($gen + 1) / ($gen * 2);
269        }
270        if ($style === self::STYLE_THREE_QUARTER_CIRCLE) {
271            $fanh *= 0.86;
272        }
273        $scale = $fanw / 640;
274
275        // Create the image
276        $image = imagecreate((int) $fanw, (int) $fanh);
277
278        // Create colors
279        $transparent = imagecolorallocate($image, 0, 0, 0);
280        imagecolortransparent($image, $transparent);
281
282        /** @var ModuleThemeInterface $theme */
283        $theme = app(ModuleThemeInterface::class);
284
285        $foreground = $this->imageColor($image, $theme->parameter('chart-font-color'));
286
287        $backgrounds = [
288            'M' => $this->imageColor($image, $theme->parameter('chart-background-m')),
289            'F' => $this->imageColor($image, $theme->parameter('chart-background-f')),
290            'U' => $this->imageColor($image, $theme->parameter('chart-background-u')),
291        ];
292
293        imagefilledrectangle($image, 0, 0, (int) $fanw, (int) $fanh, $transparent);
294
295        $fandeg = 90 * $style;
296
297        // Popup menus for each ancestor
298        $html = '';
299
300        // Areas for the imagemap
301        $areas = '';
302
303        // loop to create fan cells
304        while ($gen >= 0) {
305            // clean current generation area
306            $deg2 = 360 + ($fandeg - 180) / 2;
307            $deg1 = $deg2 - $fandeg;
308            imagefilledarc($image, (int) $cx, (int) $cy, (int) $rx, (int) $rx, (int) $deg1, (int) $deg2, $backgrounds['U'], IMG_ARC_PIE);
309            $rx -= 3;
310
311            // calculate new angle
312            $p2    = 2 ** $gen;
313            $angle = $fandeg / $p2;
314            $deg2  = 360 + ($fandeg - 180) / 2;
315            $deg1  = $deg2 - $angle;
316            // special case for rootid cell
317            if ($gen == 0) {
318                $deg1 = 90;
319                $deg2 = 360 + $deg1;
320            }
321
322            // draw each cell
323            while ($sosa >= $p2) {
324                if ($ancestors->has($sosa)) {
325                    $person  = $ancestors->get($sosa);
326                    $name    = $person->fullName();
327                    $addname = $person->alternateName();
328
329                    $text = I18N::reverseText($name);
330                    if ($addname) {
331                        $text .= "\n" . I18N::reverseText($addname);
332                    }
333
334                    $text .= "\n" . I18N::reverseText($person->getLifeSpan());
335
336                    $background = $backgrounds[$person->sex()];
337
338                    imagefilledarc($image, (int) $cx, (int) $cy, (int) $rx, (int) $rx, (int) $deg1, (int) $deg2, $background, IMG_ARC_PIE);
339
340                    // split and center text by lines
341                    $wmax = (int) ($angle * 7 / 7 * $scale);
342                    $wmax = min($wmax, 35 * $scale);
343                    if ($gen === 0) {
344                        $wmax = min($wmax, 17 * $scale);
345                    }
346                    $text = $this->splitAlignText($text, (int) $wmax);
347
348                    // text angle
349                    $tangle = 270 - ($deg1 + $angle / 2);
350                    if ($gen === 0) {
351                        $tangle = 0;
352                    }
353
354                    // calculate text position
355                    $deg = $deg1 + 0.44;
356                    if ($deg2 - $deg1 > 40) {
357                        $deg = $deg1 + ($deg2 - $deg1) / 11;
358                    }
359                    if ($deg2 - $deg1 > 80) {
360                        $deg = $deg1 + ($deg2 - $deg1) / 7;
361                    }
362                    if ($deg2 - $deg1 > 140) {
363                        $deg = $deg1 + ($deg2 - $deg1) / 4;
364                    }
365                    if ($gen === 0) {
366                        $deg = 180;
367                    }
368                    $rad = deg2rad($deg);
369                    $mr  = ($rx - $rw / 4) / 2;
370                    if ($gen > 0 && $deg2 - $deg1 > 80) {
371                        $mr = $rx / 2;
372                    }
373                    $tx = $cx + $mr * cos($rad);
374                    $ty = $cy + $mr * sin($rad);
375                    if ($sosa === 1) {
376                        $ty -= $mr / 2;
377                    }
378
379                    // print text
380                    imagettftext(
381                        $image,
382                        7,
383                        $tangle,
384                        (int) $tx,
385                        (int) $ty,
386                        $foreground,
387                        Webtrees::ROOT_DIR . 'resources/fonts/DejaVuSans.ttf',
388                        $text
389                    );
390
391                    $areas .= '<area shape="poly" coords="';
392                    // plot upper points
393                    $mr  = $rx / 2;
394                    $deg = $deg1;
395                    while ($deg <= $deg2) {
396                        $rad   = deg2rad($deg);
397                        $tx    = round($cx + $mr * cos($rad));
398                        $ty    = round($cy + $mr * sin($rad));
399                        $areas .= "$tx,$ty,";
400                        $deg   += ($deg2 - $deg1) / 6;
401                    }
402                    // plot lower points
403                    $mr  = ($rx - $rw) / 2;
404                    $deg = $deg2;
405                    while ($deg >= $deg1) {
406                        $rad   = deg2rad($deg);
407                        $tx    = round($cx + $mr * cos($rad));
408                        $ty    = round($cy + $mr * sin($rad));
409                        $areas .= "$tx,$ty,";
410                        $deg   -= ($deg2 - $deg1) / 6;
411                    }
412                    // join first point
413                    $mr    = $rx / 2;
414                    $deg   = $deg1;
415                    $rad   = deg2rad($deg);
416                    $tx    = round($cx + $mr * cos($rad));
417                    $ty    = round($cy + $mr * sin($rad));
418                    $areas .= "$tx,$ty";
419                    // add action url
420                    $areas .= '" href="#' . $person->xref() . '"';
421                    $html  .= '<div id="' . $person->xref() . '" class="fan_chart_menu">';
422                    $html  .= '<div class="person_box"><div class="details1">';
423                    $html  .= '<div class="charts">';
424                    $html  .= '<a href="' . e($person->url()) . '" class="dropdown-item">' . $name . '</a>';
425                    foreach ($theme->individualBoxMenu($person) as $menu) {
426                        $html .= '<a href="' . e($menu->getLink()) . '" class="dropdown-item p-1 ' . e($menu->getClass()) . '">' . $menu->getLabel() . '</a>';
427                    }
428                    $html  .= '</div>';
429                    $html  .= '</div></div>';
430                    $html  .= '</div>';
431                    $areas .= ' alt="' . strip_tags($person->fullName()) . '" title="' . strip_tags($person->fullName()) . '">';
432                }
433                $deg1 -= $angle;
434                $deg2 -= $angle;
435                $sosa--;
436            }
437            $rx -= $rw;
438            $gen--;
439        }
440
441        ob_start();
442        imagepng($image);
443        imagedestroy($image);
444        $png = ob_get_clean();
445
446        return response(view('modules/fanchart/chart', [
447            'fanh'  => $fanh,
448            'fanw'  => $fanw,
449            'html'  => $html,
450            'areas' => $areas,
451            'png'   => $png,
452            'title' => $this->chartTitle($individual),
453        ]));
454    }
455
456    /**
457     * split and center text by lines
458     *
459     * @param string $data   input string
460     * @param int    $maxlen max length of each line
461     *
462     * @return string $text output string
463     */
464    protected function splitAlignText(string $data, int $maxlen): string
465    {
466        $RTLOrd = [
467            215,
468            216,
469            217,
470            218,
471            219,
472        ];
473
474        $lines = explode("\n", $data);
475        // more than 1 line : recursive calls
476        if (count($lines) > 1) {
477            $text = '';
478            foreach ($lines as $line) {
479                $text .= $this->splitAlignText($line, $maxlen) . "\n";
480            }
481
482            return $text;
483        }
484        // process current line word by word
485        $split = explode(' ', $data);
486        $text  = '';
487        $line  = '';
488
489        // do not split hebrew line
490        $found = false;
491        foreach ($RTLOrd as $ord) {
492            if (strpos($data, chr($ord)) !== false) {
493                $found = true;
494            }
495        }
496        if ($found) {
497            $line = $data;
498        } else {
499            foreach ($split as $word) {
500                $len  = strlen($line);
501                $wlen = strlen($word);
502                if (($len + $wlen) < $maxlen) {
503                    if ($line !== '') {
504                        $line .= ' ';
505                    }
506                    $line .= $word;
507                } else {
508                    $p = max(0, (int) (($maxlen - $len) / 2));
509                    if ($line !== '') {
510                        $line = str_repeat(' ', $p) . $line; // center alignment using spaces
511                        $text .= $line . "\n";
512                    }
513                    $line = $word;
514                }
515            }
516        }
517        // last line
518        if ($line !== '') {
519            $len = strlen($line);
520            if (in_array(ord($line[0]), $RTLOrd, true)) {
521                $len /= 2;
522            }
523            $p    = max(0, (int) (($maxlen - $len) / 2));
524            $line = str_repeat(' ', $p) . $line; // center alignment using spaces
525            $text .= $line;
526        }
527
528        return $text;
529    }
530
531    /**
532     * Convert a CSS color into a GD color.
533     *
534     * @param resource $image
535     * @param string   $css_color
536     *
537     * @return int
538     */
539    protected function imageColor($image, string $css_color): int
540    {
541        return imagecolorallocate(
542            $image,
543            (int) hexdec(substr($css_color, 0, 2)),
544            (int) hexdec(substr($css_color, 2, 2)),
545            (int) hexdec(substr($css_color, 4, 2))
546        );
547    }
548
549    /**
550     * This chart can display its output in a number of styles
551     *
552     * @return array
553     */
554    protected function styles(): array
555    {
556        return [
557            /* I18N: layout option for the fan chart */
558            self::STYLE_HALF_CIRCLE          => I18N::translate('half circle'),
559            /* I18N: layout option for the fan chart */
560            self::STYLE_THREE_QUARTER_CIRCLE => I18N::translate('three-quarter circle'),
561            /* I18N: layout option for the fan chart */
562            self::STYLE_FULL_CIRCLE          => I18N::translate('full circle'),
563        ];
564    }
565}
566