xref: /webtrees/app/Module/RelationshipsChartModule.php (revision f735852025b7cf25907aa75da63403e46a63b49b)
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 Closure;
24use Fig\Http\Message\RequestMethodInterface;
25use Fisharebest\Algorithm\Dijkstra;
26use Fisharebest\Webtrees\Auth;
27use Fisharebest\Webtrees\Family;
28use Fisharebest\Webtrees\FlashMessages;
29use Fisharebest\Webtrees\Functions\Functions;
30use Fisharebest\Webtrees\I18N;
31use Fisharebest\Webtrees\Individual;
32use Fisharebest\Webtrees\Menu;
33use Fisharebest\Webtrees\Services\TreeService;
34use Fisharebest\Webtrees\Tree;
35use Illuminate\Database\Capsule\Manager as DB;
36use Illuminate\Database\Query\JoinClause;
37use Psr\Http\Message\ResponseInterface;
38use Psr\Http\Message\ServerRequestInterface;
39use Psr\Http\Server\RequestHandlerInterface;
40
41use function app;
42use function assert;
43use function redirect;
44use function route;
45use function view;
46
47/**
48 * Class RelationshipsChartModule
49 */
50class RelationshipsChartModule extends AbstractModule implements ModuleChartInterface, RequestHandlerInterface
51{
52    use ModuleChartTrait;
53    use ModuleConfigTrait;
54
55    private const ROUTE_NAME = 'relationships';
56    private const ROUTE_URL  = '/tree/{tree}/relationships-{ancestors}-{recursion}/{xref}{/xref2}';
57
58    /** It would be more correct to use PHP_INT_MAX, but this isn't friendly in URLs */
59    public const UNLIMITED_RECURSION = 99;
60
61    /** By default new trees allow unlimited recursion */
62    public const DEFAULT_RECURSION = '99';
63
64    /** By default new trees search for all relationships (not via ancestors) */
65    public const DEFAULT_ANCESTORS  = '0';
66    public const DEFAULT_PARAMETERS = [
67        'ancestors' => self::DEFAULT_ANCESTORS,
68        'recursion' => self::DEFAULT_RECURSION,
69    ];
70
71    /** @var TreeService */
72    private $tree_service;
73
74    /**
75     * ModuleController constructor.
76     *
77     * @param TreeService   $tree_service
78     */
79    public function __construct(TreeService $tree_service)
80    {
81        $this->tree_service = $tree_service;
82    }
83
84    /**
85     * Initialization.
86     *
87     * @return void
88     */
89    public function boot(): void
90    {
91        $router_container = app(RouterContainer::class);
92        assert($router_container instanceof RouterContainer);
93
94        $router_container->getMap()
95            ->get(self::ROUTE_NAME, self::ROUTE_URL, $this)
96            ->allows(RequestMethodInterface::METHOD_POST)
97            ->tokens([
98                'ancestors' => '\d+',
99                'recursion' => '\d+',
100            ]);
101    }
102
103    /**
104     * A sentence describing what this module does.
105     *
106     * @return string
107     */
108    public function description(): string
109    {
110        /* I18N: Description of the “RelationshipsChart” module */
111        return I18N::translate('A chart displaying relationships between two individuals.');
112    }
113
114    /**
115     * Return a menu item for this chart - for use in individual boxes.
116     *
117     * @param Individual $individual
118     *
119     * @return Menu|null
120     */
121    public function chartBoxMenu(Individual $individual): ?Menu
122    {
123        return $this->chartMenu($individual);
124    }
125
126    /**
127     * A main menu item for this chart.
128     *
129     * @param Individual $individual
130     *
131     * @return Menu
132     */
133    public function chartMenu(Individual $individual): Menu
134    {
135        $gedcomid = $individual->tree()->getUserPreference(Auth::user(), 'gedcomid');
136
137        if ($gedcomid !== '' && $gedcomid !== $individual->xref()) {
138            return new Menu(
139                I18N::translate('Relationship to me'),
140                $this->chartUrl($individual, ['xref2' => $gedcomid]),
141                $this->chartMenuClass(),
142                $this->chartUrlAttributes()
143            );
144        }
145
146        return new Menu(
147            $this->title(),
148            $this->chartUrl($individual),
149            $this->chartMenuClass(),
150            $this->chartUrlAttributes()
151        );
152    }
153
154    /**
155     * CSS class for the URL.
156     *
157     * @return string
158     */
159    public function chartMenuClass(): string
160    {
161        return 'menu-chart-relationship';
162    }
163
164    /**
165     * How should this module be identified in the control panel, etc.?
166     *
167     * @return string
168     */
169    public function title(): string
170    {
171        /* I18N: Name of a module/chart */
172        return I18N::translate('Relationships');
173    }
174
175    /**
176     * The URL for a page showing chart options.
177     *
178     * @param Individual $individual
179     * @param mixed[]    $parameters
180     *
181     * @return string
182     */
183    public function chartUrl(Individual $individual, array $parameters = []): string
184    {
185        return route(self::ROUTE_NAME, [
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        $ajax      = $request->getQueryParams()['ajax'] ?? '';
199        $ancestors = (int) $request->getAttribute('ancestors');
200        $recursion = (int) $request->getAttribute('recursion');
201        $tree      = $request->getAttribute('tree');
202        $user      = $request->getAttribute('user');
203        $xref      = $request->getAttribute('xref');
204        $xref2     = $request->getAttribute('xref2') ?? '';
205
206        // Convert POST requests into GET requests for pretty URLs.
207        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
208            return redirect(route(self::ROUTE_NAME, [
209                'ancestors' => $request->getParsedBody()['ancestors'],
210                'recursion' => $request->getParsedBody()['recursion'],
211                'tree'      => $request->getAttribute('tree')->name(),
212                'xref'      => $request->getParsedBody()['xref'],
213                'xref2'     => $request->getParsedBody()['xref2'],
214            ]));
215        }
216
217        $individual1 = Individual::getInstance($xref, $tree);
218        $individual2 = Individual::getInstance($xref2, $tree);
219
220        $ancestors_only = (int) $tree->getPreference('RELATIONSHIP_ANCESTORS', static::DEFAULT_ANCESTORS);
221        $max_recursion  = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
222
223        $recursion = min($recursion, $max_recursion);
224
225        if ($tree->getPreference('SHOW_PRIVATE_RELATIONSHIPS') !== '1') {
226            if ($individual1 instanceof Individual) {
227                Auth::checkIndividualAccess($individual1);
228            }
229
230            if ($individual2 instanceof Individual) {
231                Auth::checkIndividualAccess($individual2);
232            }
233        }
234
235        Auth::checkComponentAccess($this, 'chart', $tree, $user);
236
237        if ($individual1 instanceof Individual && $individual2 instanceof Individual) {
238            if ($ajax === '1') {
239                return $this->chart($individual1, $individual2, $recursion, $ancestors);
240            }
241
242            /* I18N: %s are individual’s names */
243            $title    = I18N::translate('Relationships between %1$s and %2$s', $individual1->fullName(), $individual2->fullName());
244            $ajax_url = $this->chartUrl($individual1, [
245                'ajax'      => true,
246                'ancestors' => $ancestors,
247                'recursion' => $recursion,
248                'xref2'     => $individual2->xref(),
249            ]);
250        } else {
251            $title    = I18N::translate('Relationships');
252            $ajax_url = '';
253        }
254
255        return $this->viewResponse('modules/relationships-chart/page', [
256            'ajax_url'          => $ajax_url,
257            'ancestors'         => $ancestors,
258            'ancestors_only'    => $ancestors_only,
259            'ancestors_options' => $this->ancestorsOptions(),
260            'individual1'       => $individual1,
261            'individual2'       => $individual2,
262            'max_recursion'     => $max_recursion,
263            'module'            => $this->name(),
264            'recursion'         => $recursion,
265            'recursion_options' => $this->recursionOptions($max_recursion),
266            'title'             => $title,
267            'tree'              => $tree,
268        ]);
269    }
270
271    /**
272     * @param Individual $individual1
273     * @param Individual $individual2
274     * @param int        $recursion
275     * @param int        $ancestors
276     *
277     * @return ResponseInterface
278     */
279    public function chart(Individual $individual1, Individual $individual2, int $recursion, int $ancestors): ResponseInterface
280    {
281        $tree = $individual1->tree();
282
283        $max_recursion = (int) $tree->getPreference('RELATIONSHIP_RECURSION', static::DEFAULT_RECURSION);
284
285        $recursion = min($recursion, $max_recursion);
286
287        $paths = $this->calculateRelationships($individual1, $individual2, $recursion, (bool) $ancestors);
288
289        // @TODO - convert to views
290        ob_start();
291        if (I18N::direction() === 'ltr') {
292            $diagonal1 = asset('css/images/dline.png');
293            $diagonal2 = asset('css/images/dline2.png');
294        } else {
295            $diagonal1 = asset('css/images/dline2.png');
296            $diagonal2 = asset('css/images/dline.png');
297        }
298
299        $num_paths = 0;
300        foreach ($paths as $path) {
301            // Extract the relationship names between pairs of individuals
302            $relationships = $this->oldStyleRelationshipPath($tree, $path);
303            if (empty($relationships)) {
304                // Cannot see one of the families/individuals, due to privacy;
305                continue;
306            }
307            echo '<h3>', I18N::translate('Relationship: %s', Functions::getRelationshipNameFromPath(implode('', $relationships), $individual1, $individual2)), '</h3>';
308            $num_paths++;
309
310            // Use a table/grid for layout.
311            $table = [];
312            // Current position in the grid.
313            $x = 0;
314            $y = 0;
315            // Extent of the grid.
316            $min_y = 0;
317            $max_y = 0;
318            $max_x = 0;
319            // For each node in the path.
320            foreach ($path as $n => $xref) {
321                if ($n % 2 === 1) {
322                    switch ($relationships[$n]) {
323                        case 'hus':
324                        case 'wif':
325                        case 'spo':
326                        case 'bro':
327                        case 'sis':
328                        case 'sib':
329                            $table[$x + 1][$y] = '<div style="background:url(' . e(asset('css/images/hline.png')) . ') repeat-x center;  width: 94px; text-align: center"><div class="hline-text" style="height: 32px;">' . Functions::getRelationshipNameFromPath($relationships[$n], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($path[$n + 1], $tree)) . '</div><div style="height: 32px;">' . view('icons/arrow-right') . '</div></div>';
330                            $x                 += 2;
331                            break;
332                        case 'son':
333                        case 'dau':
334                        case 'chi':
335                            if ($n > 2 && preg_match('/fat|mot|par/', $relationships[$n - 2])) {
336                                $table[$x + 1][$y - 1] = '<div style="background:url(' . $diagonal2 . '); width: 64px; height: 64px; text-align: center;"><div style="height: 32px; text-align: end;">' . Functions::getRelationshipNameFromPath($relationships[$n], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($path[$n + 1], $tree)) . '</div><div style="height: 32px; text-align: start;">' . view('icons/arrow-down') . '</div></div>';
337                                $x                     += 2;
338                            } else {
339                                $table[$x][$y - 1] = '<div style="background:url(' . e('"' . asset('css/images/vline.png') . '"') . ') repeat-y center; height: 64px; text-align: center;"><div class="vline-text" style="display: inline-block; width:50%; line-height: 64px;">' . Functions::getRelationshipNameFromPath($relationships[$n], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($path[$n + 1], $tree)) . '</div><div style="display: inline-block; width:50%; line-height: 64px;">' . view('icons/arrow-down') . '</div></div>';
340                            }
341                            $y -= 2;
342                            break;
343                        case 'fat':
344                        case 'mot':
345                        case 'par':
346                            if ($n > 2 && preg_match('/son|dau|chi/', $relationships[$n - 2])) {
347                                $table[$x + 1][$y + 1] = '<div style="background:url(' . $diagonal1 . '); background-position: top right; width: 64px; height: 64px; text-align: center;"><div style="height: 32px; text-align: start;">' . Functions::getRelationshipNameFromPath($relationships[$n], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($path[$n + 1], $tree)) . '</div><div style="height: 32px; text-align: end;">' . view('icons/arrow-down') . '</div></div>';
348                                $x                     += 2;
349                            } else {
350                                $table[$x][$y + 1] = '<div style="background:url(' . e('"' . asset('css/images/vline.png') . '"') . ') repeat-y center; height: 64px; text-align:center; "><div class="vline-text" style="display: inline-block; width: 50%; line-height: 64px;">' . Functions::getRelationshipNameFromPath($relationships[$n], Individual::getInstance($path[$n - 1], $tree), Individual::getInstance($path[$n + 1], $tree)) . '</div><div style="display: inline-block; width: 50%; line-height: 32px">' . view('icons/arrow-up') . '</div></div>';
351                            }
352                            $y += 2;
353                            break;
354                    }
355                    $max_x = max($max_x, $x);
356                    $min_y = min($min_y, $y);
357                    $max_y = max($max_y, $y);
358                } else {
359                    $individual    = Individual::getInstance($xref, $tree);
360                    $table[$x][$y] = view('chart-box', ['individual' => $individual]);
361                }
362            }
363            echo '<div class="wt-chart wt-chart-relationships">';
364            echo '<table style="border-collapse: collapse; margin: 20px 50px;">';
365            for ($y = $max_y; $y >= $min_y; --$y) {
366                echo '<tr>';
367                for ($x = 0; $x <= $max_x; ++$x) {
368                    echo '<td style="padding: 0;">';
369                    if (isset($table[$x][$y])) {
370                        echo $table[$x][$y];
371                    }
372                    echo '</td>';
373                }
374                echo '</tr>';
375            }
376            echo '</table>';
377            echo '</div>';
378        }
379
380        if (!$num_paths) {
381            echo '<p>', I18N::translate('No link between the two individuals could be found.'), '</p>';
382        }
383
384        $html = ob_get_clean();
385
386        return response($html);
387    }
388
389    /**
390     * @param ServerRequestInterface $request
391     *
392     * @return ResponseInterface
393     */
394    public function getAdminAction(ServerRequestInterface $request): ResponseInterface
395    {
396        $this->layout = 'layouts/administration';
397
398        return $this->viewResponse('modules/relationships-chart/config', [
399            'all_trees'         => $this->tree_service->all(),
400            'ancestors_options' => $this->ancestorsOptions(),
401            'default_ancestors' => self::DEFAULT_ANCESTORS,
402            'default_recursion' => self::DEFAULT_RECURSION,
403            'recursion_options' => $this->recursionConfigOptions(),
404            'title'             => I18N::translate('Chart preferences') . ' — ' . $this->title(),
405        ]);
406    }
407
408    /**
409     * @param ServerRequestInterface $request
410     *
411     * @return ResponseInterface
412     */
413    public function postAdminAction(ServerRequestInterface $request): ResponseInterface
414    {
415        foreach ($this->tree_service->all() as $tree) {
416            $recursion = $request->getParsedBody()['relationship-recursion-' . $tree->id()] ?? '';
417            $ancestors = $request->getParsedBody()['relationship-ancestors-' . $tree->id()] ?? '';
418
419            $tree->setPreference('RELATIONSHIP_RECURSION', $recursion);
420            $tree->setPreference('RELATIONSHIP_ANCESTORS', $ancestors);
421        }
422
423        FlashMessages::addMessage(I18N::translate('The preferences for the module “%s” have been updated.', $this->title()), 'success');
424
425        return redirect($this->getConfigLink());
426    }
427
428    /**
429     * Possible options for the ancestors option
430     *
431     * @return string[]
432     */
433    private function ancestorsOptions(): array
434    {
435        return [
436            0 => I18N::translate('Find any relationship'),
437            1 => I18N::translate('Find relationships via ancestors'),
438        ];
439    }
440
441    /**
442     * Possible options for the recursion option
443     *
444     * @return string[]
445     */
446    private function recursionConfigOptions(): array
447    {
448        return [
449            0                         => I18N::translate('none'),
450            1                         => I18N::number(1),
451            2                         => I18N::number(2),
452            3                         => I18N::number(3),
453            self::UNLIMITED_RECURSION => I18N::translate('unlimited'),
454        ];
455    }
456
457    /**
458     * Calculate the shortest paths - or all paths - between two individuals.
459     *
460     * @param Individual $individual1
461     * @param Individual $individual2
462     * @param int        $recursion How many levels of recursion to use
463     * @param bool       $ancestor  Restrict to relationships via a common ancestor
464     *
465     * @return string[][]
466     */
467    private function calculateRelationships(Individual $individual1, Individual $individual2, $recursion, $ancestor = false): array
468    {
469        $tree = $individual1->tree();
470
471        $rows = DB::table('link')
472            ->where('l_file', '=', $tree->id())
473            ->whereIn('l_type', ['FAMS', 'FAMC'])
474            ->select(['l_from', 'l_to'])
475            ->get();
476
477        // Optionally restrict the graph to the ancestors of the individuals.
478        if ($ancestor) {
479            $ancestors = $this->allAncestors($individual1->xref(), $individual2->xref(), $tree->id());
480            $exclude   = $this->excludeFamilies($individual1->xref(), $individual2->xref(), $tree->id());
481        } else {
482            $ancestors = [];
483            $exclude   = [];
484        }
485
486        $graph = [];
487
488        foreach ($rows as $row) {
489            if (empty($ancestors) || in_array($row->l_from, $ancestors, true) && !in_array($row->l_to, $exclude, true)) {
490                $graph[$row->l_from][$row->l_to] = 1;
491                $graph[$row->l_to][$row->l_from] = 1;
492            }
493        }
494
495        $xref1    = $individual1->xref();
496        $xref2    = $individual2->xref();
497        $dijkstra = new Dijkstra($graph);
498        $paths    = $dijkstra->shortestPaths($xref1, $xref2);
499
500        // Only process each exclusion list once;
501        $excluded = [];
502
503        $queue = [];
504        foreach ($paths as $path) {
505            // Insert the paths into the queue, with an exclusion list.
506            $queue[] = [
507                'path'    => $path,
508                'exclude' => [],
509            ];
510            // While there are un-extended paths
511            for ($next = current($queue); $next !== false; $next = next($queue)) {
512                // For each family on the path
513                for ($n = count($next['path']) - 2; $n >= 1; $n -= 2) {
514                    $exclude = $next['exclude'];
515                    if (count($exclude) >= $recursion) {
516                        continue;
517                    }
518                    $exclude[] = $next['path'][$n];
519                    sort($exclude);
520                    $tmp = implode('-', $exclude);
521                    if (in_array($tmp, $excluded, true)) {
522                        continue;
523                    }
524
525                    $excluded[] = $tmp;
526                    // Add any new path to the queue
527                    foreach ($dijkstra->shortestPaths($xref1, $xref2, $exclude) as $new_path) {
528                        $queue[] = [
529                            'path'    => $new_path,
530                            'exclude' => $exclude,
531                        ];
532                    }
533                }
534            }
535        }
536        // Extract the paths from the queue.
537        $paths = [];
538        foreach ($queue as $next) {
539            // The Dijkstra library does not use strict types, and converts
540            // numeric array keys (XREFs) from strings to integers;
541            $path = array_map($this->stringMapper(), $next['path']);
542
543            // Remove duplicates
544            $paths[implode('-', $next['path'])] = $path;
545        }
546
547        return $paths;
548    }
549
550    /**
551     * Convert numeric values to strings
552     *
553     * @return Closure
554     */
555    private function stringMapper(): Closure
556    {
557        return static function ($xref) {
558            return (string) $xref;
559        };
560    }
561
562    /**
563     * Find all ancestors of a list of individuals
564     *
565     * @param string $xref1
566     * @param string $xref2
567     * @param int    $tree_id
568     *
569     * @return string[]
570     */
571    private function allAncestors($xref1, $xref2, $tree_id): array
572    {
573        $ancestors = [
574            $xref1,
575            $xref2,
576        ];
577
578        $queue = [
579            $xref1,
580            $xref2,
581        ];
582        while (!empty($queue)) {
583            $parents = DB::table('link AS l1')
584                ->join('link AS l2', static function (JoinClause $join): void {
585                    $join
586                        ->on('l1.l_to', '=', 'l2.l_to')
587                        ->on('l1.l_file', '=', 'l2.l_file');
588                })
589                ->where('l1.l_file', '=', $tree_id)
590                ->where('l1.l_type', '=', 'FAMC')
591                ->where('l2.l_type', '=', 'FAMS')
592                ->whereIn('l1.l_from', $queue)
593                ->pluck('l2.l_from');
594
595            $queue = [];
596            foreach ($parents as $parent) {
597                if (!in_array($parent, $ancestors, true)) {
598                    $ancestors[] = $parent;
599                    $queue[]     = $parent;
600                }
601            }
602        }
603
604        return $ancestors;
605    }
606
607    /**
608     * Find all families of two individuals
609     *
610     * @param string $xref1
611     * @param string $xref2
612     * @param int    $tree_id
613     *
614     * @return string[]
615     */
616    private function excludeFamilies($xref1, $xref2, $tree_id): array
617    {
618        return DB::table('link AS l1')
619            ->join('link AS l2', static function (JoinClause $join): void {
620                $join
621                    ->on('l1.l_to', '=', 'l2.l_to')
622                    ->on('l1.l_type', '=', 'l2.l_type')
623                    ->on('l1.l_file', '=', 'l2.l_file');
624            })
625            ->where('l1.l_file', '=', $tree_id)
626            ->where('l1.l_type', '=', 'FAMS')
627            ->where('l1.l_from', '=', $xref1)
628            ->where('l2.l_from', '=', $xref2)
629            ->pluck('l1.l_to')
630            ->all();
631    }
632
633    /**
634     * Convert a path (list of XREFs) to an "old-style" string of relationships.
635     * Return an empty array, if privacy rules prevent us viewing any node.
636     *
637     * @param Tree     $tree
638     * @param string[] $path Alternately Individual / Family
639     *
640     * @return string[]
641     */
642    private function oldStyleRelationshipPath(Tree $tree, array $path): array
643    {
644        $spouse_codes  = [
645            'M' => 'hus',
646            'F' => 'wif',
647            'U' => 'spo',
648        ];
649        $parent_codes  = [
650            'M' => 'fat',
651            'F' => 'mot',
652            'U' => 'par',
653        ];
654        $child_codes   = [
655            'M' => 'son',
656            'F' => 'dau',
657            'U' => 'chi',
658        ];
659        $sibling_codes = [
660            'M' => 'bro',
661            'F' => 'sis',
662            'U' => 'sib',
663        ];
664        $relationships = [];
665
666        for ($i = 1, $count = count($path); $i < $count; $i += 2) {
667            $family = Family::getInstance($path[$i], $tree);
668            $prev   = Individual::getInstance($path[$i - 1], $tree);
669            $next   = Individual::getInstance($path[$i + 1], $tree);
670            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $prev->xref() . '@/', $family->gedcom(), $match)) {
671                $rel1 = $match[1];
672            } else {
673                return [];
674            }
675            if (preg_match('/\n\d (HUSB|WIFE|CHIL) @' . $next->xref() . '@/', $family->gedcom(), $match)) {
676                $rel2 = $match[1];
677            } else {
678                return [];
679            }
680            if (($rel1 === 'HUSB' || $rel1 === 'WIFE') && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
681                $relationships[$i] = $spouse_codes[$next->sex()];
682            } elseif (($rel1 === 'HUSB' || $rel1 === 'WIFE') && $rel2 === 'CHIL') {
683                $relationships[$i] = $child_codes[$next->sex()];
684            } elseif ($rel1 === 'CHIL' && ($rel2 === 'HUSB' || $rel2 === 'WIFE')) {
685                $relationships[$i] = $parent_codes[$next->sex()];
686            } elseif ($rel1 === 'CHIL' && $rel2 === 'CHIL') {
687                $relationships[$i] = $sibling_codes[$next->sex()];
688            }
689        }
690
691        return $relationships;
692    }
693
694    /**
695     * Possible options for the recursion option
696     *
697     * @param int $max_recursion
698     *
699     * @return string[]
700     */
701    private function recursionOptions(int $max_recursion): array
702    {
703        if ($max_recursion === static::UNLIMITED_RECURSION) {
704            $text = I18N::translate('Find all possible relationships');
705        } else {
706            $text = I18N::translate('Find other relationships');
707        }
708
709        return [
710            '0'            => I18N::translate('Find the closest relationships'),
711            $max_recursion => $text,
712        ];
713    }
714}
715