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