xref: /webtrees/app/Module/BranchesListModule.php (revision 76d39c55735cfa9ad0972b0dd530e96b051f9ebe)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Module;
21
22use Aura\Router\RouterContainer;
23use Fig\Http\Message\RequestMethodInterface;
24use Fisharebest\Webtrees\Auth;
25use Fisharebest\Webtrees\Contracts\UserInterface;
26use Fisharebest\Webtrees\Family;
27use Fisharebest\Webtrees\GedcomRecord;
28use Fisharebest\Webtrees\I18N;
29use Fisharebest\Webtrees\Individual;
30use Fisharebest\Webtrees\Registry;
31use Fisharebest\Webtrees\Services\ModuleService;
32use Fisharebest\Webtrees\Soundex;
33use Fisharebest\Webtrees\Tree;
34use Illuminate\Database\Capsule\Manager as DB;
35use Illuminate\Database\Query\Builder;
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 array_search;
43use function assert;
44use function e;
45use function explode;
46use function in_array;
47use function is_int;
48use function key;
49use function log;
50use function next;
51use function redirect;
52use function route;
53use function strip_tags;
54use function stripos;
55use function strtolower;
56use function usort;
57use function view;
58
59/**
60 * Class BranchesListModule
61 */
62class BranchesListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
63{
64    use ModuleListTrait;
65
66    protected const ROUTE_URL = '/tree/{tree}/branches{/surname}';
67
68    private ModuleService $module_service;
69
70    /**
71     * BranchesListModule constructor.
72     *
73     * @param ModuleService $module_service
74     */
75    public function __construct(ModuleService $module_service)
76    {
77        $this->module_service = $module_service;
78    }
79
80    /**
81     * Initialization.
82     *
83     * @return void
84     */
85    public function boot(): void
86    {
87        $router_container = app(RouterContainer::class);
88        assert($router_container instanceof RouterContainer);
89
90        $router_container->getMap()
91            ->get(static::class, static::ROUTE_URL, $this)
92            ->allows(RequestMethodInterface::METHOD_POST);
93    }
94
95    /**
96     * How should this module be identified in the control panel, etc.?
97     *
98     * @return string
99     */
100    public function title(): string
101    {
102        /* I18N: Name of a module/list */
103        return I18N::translate('Branches');
104    }
105
106    /**
107     * A sentence describing what this module does.
108     *
109     * @return string
110     */
111    public function description(): string
112    {
113        /* I18N: Description of the “Branches” module */
114        return I18N::translate('A list of branches of a family.');
115    }
116
117    /**
118     * CSS class for the URL.
119     *
120     * @return string
121     */
122    public function listMenuClass(): string
123    {
124        return 'menu-branches';
125    }
126
127    /**
128     * @param Tree                                      $tree
129     * @param array<bool|int|string|array<string>|null> $parameters
130     *
131     * @return string
132     */
133    public function listUrl(Tree $tree, array $parameters = []): string
134    {
135        $xref = app(ServerRequestInterface::class)->getAttribute('xref', '');
136
137        if ($xref !== '') {
138            $individual = Registry::individualFactory()->make($xref, $tree);
139
140            if ($individual instanceof Individual && $individual->canShow()) {
141                $parameters['surname'] = $parameters['surname'] ?? $individual->getAllNames()[0]['surn'] ?? null;
142            }
143        }
144
145        $parameters['tree'] = $tree->name();
146
147        return route(static::class, $parameters);
148    }
149
150    /**
151     * @return array<string>
152     */
153    public function listUrlAttributes(): array
154    {
155        return [];
156    }
157
158    /**
159     * Handle URLs generated by older versions of webtrees
160     *
161     * @param ServerRequestInterface $request
162     *
163     * @return ResponseInterface
164     */
165    public function getPageAction(ServerRequestInterface $request): ResponseInterface
166    {
167        return redirect($this->listUrl($request->getAttribute('tree'), $request->getQueryParams()));
168    }
169
170    /**
171     * @param ServerRequestInterface $request
172     *
173     * @return ResponseInterface
174     */
175    public function handle(ServerRequestInterface $request): ResponseInterface
176    {
177        $tree = $request->getAttribute('tree');
178        assert($tree instanceof Tree);
179
180        $user = $request->getAttribute('user');
181        assert($user instanceof UserInterface);
182
183        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
184
185        // Convert POST requests into GET requests for pretty URLs.
186        if ($request->getMethod() === RequestMethodInterface::METHOD_POST) {
187            return redirect($this->listUrl($tree, (array) $request->getParsedBody()));
188        }
189
190        $surname = (string) $request->getAttribute('surname');
191
192        $params      = $request->getQueryParams();
193        $ajax        = $params['ajax'] ?? '';
194        $soundex_std = (bool) ($params['soundex_std'] ?? false);
195        $soundex_dm  = (bool) ($params['soundex_dm'] ?? false);
196
197        if ($ajax === '1') {
198            $this->layout = 'layouts/ajax';
199
200            // Highlight direct-line ancestors of this individual.
201            $xref = $tree->getUserPreference($user, UserInterface::PREF_TREE_ACCOUNT_XREF);
202            $self = Registry::individualFactory()->make($xref, $tree);
203
204            if ($surname !== '') {
205                $individuals = $this->loadIndividuals($tree, $surname, $soundex_dm, $soundex_std);
206            } else {
207                $individuals = [];
208            }
209
210            if ($self instanceof Individual) {
211                $ancestors = $this->allAncestors($self);
212            } else {
213                $ancestors = [];
214            }
215
216            return $this->viewResponse('modules/branches/list', [
217                'branches' => $this->getPatriarchsHtml($tree, $individuals, $ancestors, $surname, $soundex_dm, $soundex_std),
218            ]);
219        }
220
221        if ($surname !== '') {
222            /* I18N: %s is a surname */
223            $title = I18N::translate('Branches of the %s family', e($surname));
224
225            $ajax_url = $this->listUrl($tree, $params + ['ajax' => true, 'surname' => $surname]);
226        } else {
227            /* I18N: Branches of a family tree */
228            $title = I18N::translate('Branches');
229
230            $ajax_url = '';
231        }
232
233        return $this->viewResponse('branches-page', [
234            'ajax_url'    => $ajax_url,
235            'soundex_dm'  => $soundex_dm,
236            'soundex_std' => $soundex_std,
237            'surname'     => $surname,
238            'title'       => $title,
239            'tree'        => $tree,
240        ]);
241    }
242
243    /**
244     * Find all ancestors of an individual, indexed by the Sosa-Stradonitz number.
245     *
246     * @param Individual $individual
247     *
248     * @return array<Individual>
249     */
250    private function allAncestors(Individual $individual): array
251    {
252        $ancestors = [
253            1 => $individual,
254        ];
255
256        do {
257            $sosa = key($ancestors);
258
259            $family = $ancestors[$sosa]->childFamilies()->first();
260
261            if ($family !== null) {
262                if ($family->husband() !== null) {
263                    $ancestors[$sosa * 2] = $family->husband();
264                }
265                if ($family->wife() !== null) {
266                    $ancestors[$sosa * 2 + 1] = $family->wife();
267                }
268            }
269        } while (next($ancestors));
270
271        return $ancestors;
272    }
273
274    /**
275     * Fetch all individuals with a matching surname
276     *
277     * @param Tree   $tree
278     * @param string $surname
279     * @param bool   $soundex_dm
280     * @param bool   $soundex_std
281     *
282     * @return array<Individual>
283     */
284    private function loadIndividuals(Tree $tree, string $surname, bool $soundex_dm, bool $soundex_std): array
285    {
286        $individuals = DB::table('individuals')
287            ->join('name', static function (JoinClause $join): void {
288                $join
289                    ->on('name.n_file', '=', 'individuals.i_file')
290                    ->on('name.n_id', '=', 'individuals.i_id');
291            })
292            ->where('i_file', '=', $tree->id())
293            ->where('n_type', '<>', '_MARNM')
294            ->where(static function (Builder $query) use ($surname, $soundex_dm, $soundex_std): void {
295                $query
296                    ->where('n_surn', '=', $surname)
297                    ->orWhere('n_surname', '=', $surname);
298
299                if ($soundex_std) {
300                    $sdx = Soundex::russell($surname);
301                    if ($sdx !== '') {
302                        foreach (explode(':', $sdx) as $value) {
303                            $query->orWhere('n_soundex_surn_std', 'LIKE', '%' . $value . '%');
304                        }
305                    }
306                }
307
308                if ($soundex_dm) {
309                    $sdx = Soundex::daitchMokotoff($surname);
310                    if ($sdx !== '') {
311                        foreach (explode(':', $sdx) as $value) {
312                            $query->orWhere('n_soundex_surn_dm', 'LIKE', '%' . $value . '%');
313                        }
314                    }
315                }
316            })
317            ->select(['individuals.*'])
318            ->distinct()
319            ->get()
320            ->map(Registry::individualFactory()->mapper($tree))
321            ->filter(GedcomRecord::accessFilter())
322            ->all();
323
324        usort($individuals, Individual::birthDateComparator());
325
326        return $individuals;
327    }
328
329    /**
330     * For each individual with no ancestors, list their descendants.
331     *
332     * @param Tree              $tree
333     * @param array<Individual> $individuals
334     * @param array<Individual> $ancestors
335     * @param string            $surname
336     * @param bool              $soundex_dm
337     * @param bool              $soundex_std
338     *
339     * @return string
340     */
341    private function getPatriarchsHtml(Tree $tree, array $individuals, array $ancestors, string $surname, bool $soundex_dm, bool $soundex_std): string
342    {
343        $html = '';
344        foreach ($individuals as $individual) {
345            foreach ($individual->childFamilies() as $family) {
346                foreach ($family->spouses() as $parent) {
347                    if (in_array($parent, $individuals, true)) {
348                        continue 3;
349                    }
350                }
351            }
352            $html .= $this->getDescendantsHtml($tree, $individuals, $ancestors, $surname, $soundex_dm, $soundex_std, $individual, null);
353        }
354
355        return $html;
356    }
357
358    /**
359     * Generate a recursive list of descendants of an individual.
360     * If parents are specified, we can also show the pedigree (adopted, etc.).
361     *
362     * @param Tree              $tree
363     * @param array<Individual> $individuals
364     * @param array<Individual> $ancestors
365     * @param string            $surname
366     * @param bool              $soundex_dm
367     * @param bool              $soundex_std
368     * @param Individual        $individual
369     * @param Family|null       $parents
370     *
371     * @return string
372     */
373    private function getDescendantsHtml(Tree $tree, array $individuals, array $ancestors, string $surname, bool $soundex_dm, bool $soundex_std, Individual $individual, Family $parents = null): string
374    {
375        $module = $this->module_service->findByComponent(ModuleChartInterface::class, $tree, Auth::user())->first(static function (ModuleInterface $module) {
376            return $module instanceof RelationshipsChartModule;
377        });
378
379        // A person has many names. Select the one that matches the searched surname
380        $person_name = '';
381        foreach ($individual->getAllNames() as $name) {
382            [$surn1] = explode(',', $name['sort']);
383            if ($this->surnamesMatch($surn1, $surname, $soundex_std, $soundex_dm)) {
384                $person_name = $name['full'];
385                break;
386            }
387        }
388
389        // No matching name? Typically children with a different surname. The branch stops here.
390        if ($person_name === '') {
391            return '<li title="' . strip_tags($individual->fullName()) . '" class="wt-branch-split"><small>' . view('icons/sex', ['sex' => $individual->sex()]) . '</small>…</li>';
392        }
393
394        // Is this individual one of our ancestors?
395        $sosa = array_search($individual, $ancestors, true);
396        if (is_int($sosa) && $module instanceof RelationshipsChartModule) {
397            $sosa_class = 'search_hit';
398            $sosa_html  = ' <a class="small wt-chart-box-' . strtolower($individual->sex()) . '" href="' . e($module->chartUrl($individual, ['xref2' => $ancestors[1]->xref()])) . '" rel="nofollow" title="' . I18N::translate('Relationship') . '">' . I18N::number($sosa) . '</a>' . self::sosaGeneration($sosa);
399        } else {
400            $sosa_class = '';
401            $sosa_html  = '';
402        }
403
404        // Generate HTML for this individual, and all their descendants
405        $indi_html = '<small>' . view('icons/sex', ['sex' => $individual->sex()]) . '</small><a class="' . $sosa_class . '" href="' . e($individual->url()) . '">' . $person_name . '</a> ' . $individual->lifespan() . $sosa_html;
406
407        // If this is not a birth pedigree (e.g. an adoption), highlight it
408        if ($parents) {
409            foreach ($individual->facts(['FAMC']) as $fact) {
410                if ($fact->target() === $parents) {
411                    $pedi = $fact->attribute('PEDI');
412
413                    if ($pedi !== '' && $pedi !== 'birth') {
414                        $pedigree  = Registry::elementFactory()->make('INDI:FAMC:PEDI')->value($pedi, $tree);
415                        $indi_html = '<span class="red">' . $pedigree . '</span> ' . $indi_html;
416                    }
417                    break;
418                }
419            }
420        }
421
422        // spouses and children
423        $spouse_families = $individual->spouseFamilies()
424            ->sort(Family::marriageDateComparator());
425
426        if ($spouse_families->isNotEmpty()) {
427            $fam_html = '';
428            foreach ($spouse_families as $family) {
429                $fam_html .= $indi_html; // Repeat the individual details for each spouse.
430
431                $spouse = $family->spouse($individual);
432                if ($spouse instanceof Individual) {
433                    $sosa = array_search($spouse, $ancestors, true);
434                    if (is_int($sosa) && $module instanceof RelationshipsChartModule) {
435                        $sosa_class = 'search_hit';
436                        $sosa_html  = ' <a class="small wt-chart-box-' . strtolower($spouse->sex()) . '" href="' . e($module->chartUrl($spouse, ['xref2' => $ancestors[1]->xref()])) . '" rel="nofollow" title="' . I18N::translate('Relationship') . '">' . I18N::number($sosa) . '</a>' . self::sosaGeneration($sosa);
437                    } else {
438                        $sosa_class = '';
439                        $sosa_html  = '';
440                    }
441                    $marriage_year = $family->getMarriageYear();
442                    if ($marriage_year) {
443                        $fam_html .= ' <a href="' . e($family->url()) . '" title="' . strip_tags($family->getMarriageDate()->display()) . '"><i class="icon-rings"></i>' . $marriage_year . '</a>';
444                    } elseif ($family->facts(['MARR'])->isNotEmpty()) {
445                        $fam_html .= ' <a href="' . e($family->url()) . '" title="' . I18N::translate('Marriage') . '"><i class="icon-rings"></i></a>';
446                    } else {
447                        $fam_html .= ' <a href="' . e($family->url()) . '" title="' . I18N::translate('Not married') . '"><i class="icon-rings"></i></a>';
448                    }
449                    $fam_html .= ' <small>' . view('icons/sex', ['sex' => $spouse->sex()]) . '</small><a class="' . $sosa_class . '" href="' . e($spouse->url()) . '">' . $spouse->fullName() . '</a> ' . $spouse->lifespan() . ' ' . $sosa_html;
450                }
451
452                $fam_html .= '<ol>';
453                foreach ($family->children() as $child) {
454                    $fam_html .= $this->getDescendantsHtml($tree, $individuals, $ancestors, $surname, $soundex_dm, $soundex_std, $child, $family);
455                }
456                $fam_html .= '</ol>';
457            }
458
459            return '<li>' . $fam_html . '</li>';
460        }
461
462        // No spouses - just show the individual
463        return '<li>' . $indi_html . '</li>';
464    }
465
466    /**
467     * Do two surnames match?
468     *
469     * @param string $surname1
470     * @param string $surname2
471     * @param bool   $soundex_std
472     * @param bool   $soundex_dm
473     *
474     * @return bool
475     */
476    private function surnamesMatch(string $surname1, string $surname2, bool $soundex_std, bool $soundex_dm): bool
477    {
478        // One name sounds like another?
479        if ($soundex_std && Soundex::compare(Soundex::russell($surname1), Soundex::russell($surname2))) {
480            return true;
481        }
482        if ($soundex_dm && Soundex::compare(Soundex::daitchMokotoff($surname1), Soundex::daitchMokotoff($surname2))) {
483            return true;
484        }
485
486        // One is a substring of the other.  e.g. Halen / Van Halen
487        return stripos($surname1, $surname2) !== false || stripos($surname2, $surname1) !== false;
488    }
489
490    /**
491     * Convert a SOSA number into a generation number. e.g. 8 = great-grandfather = 3 generations
492     *
493     * @param int $sosa
494     *
495     * @return string
496     */
497    private static function sosaGeneration(int $sosa): string
498    {
499        $generation = (int) log($sosa, 2) + 1;
500
501        return '<sup title="' . I18N::translate('Generation') . '">' . $generation . '</sup>';
502    }
503}
504