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