xref: /webtrees/app/Module/BranchesListModule.php (revision 4b9213b33377fa752da3c34c8057f8662b73fd24)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 Fig\Http\Message\RequestMethodInterface;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\Elements\PedigreeLinkageType;
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 Fisharebest\Webtrees\Validator;
35use Illuminate\Database\Capsule\Manager as DB;
36use Illuminate\Database\Query\Builder;
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 array_search;
44use function assert;
45use function e;
46use function explode;
47use function in_array;
48use function is_int;
49use function key;
50use function log;
51use function next;
52use function redirect;
53use function route;
54use function strip_tags;
55use function stripos;
56use function strtolower;
57use function usort;
58use function view;
59
60/**
61 * Class BranchesListModule
62 */
63class BranchesListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
64{
65    use ModuleListTrait;
66
67    protected const ROUTE_URL = '/tree/{tree}/branches{/surname}';
68
69    private ModuleService $module_service;
70
71    /**
72     * BranchesListModule constructor.
73     *
74     * @param ModuleService $module_service
75     */
76    public function __construct(ModuleService $module_service)
77    {
78        $this->module_service = $module_service;
79    }
80
81    /**
82     * Initialization.
83     *
84     * @return void
85     */
86    public function boot(): void
87    {
88        Registry::routeFactory()->routeMap()
89            ->get(static::class, static::ROUTE_URL, $this)
90            ->allows(RequestMethodInterface::METHOD_POST);
91    }
92
93    /**
94     * How should this module be identified in the control panel, etc.?
95     *
96     * @return string
97     */
98    public function title(): string
99    {
100        /* I18N: Name of a module/list */
101        return I18N::translate('Branches');
102    }
103
104    /**
105     * A sentence describing what this module does.
106     *
107     * @return string
108     */
109    public function description(): string
110    {
111        /* I18N: Description of the “Branches” module */
112        return I18N::translate('A list of branches of a family.');
113    }
114
115    /**
116     * CSS class for the URL.
117     *
118     * @return string
119     */
120    public function listMenuClass(): string
121    {
122        return 'menu-branches';
123    }
124
125    /**
126     * @param Tree                                      $tree
127     * @param array<bool|int|string|array<string>|null> $parameters
128     *
129     * @return string
130     */
131    public function listUrl(Tree $tree, array $parameters = []): string
132    {
133        $request = app(ServerRequestInterface::class);
134        assert($request instanceof ServerRequestInterface);
135
136        $xref = Validator::attributes($request)->isXref()->string('xref', '');
137
138        if ($xref !== '') {
139            $individual = Registry::individualFactory()->make($xref, $tree);
140
141            if ($individual instanceof Individual && $individual->canShow()) {
142                $parameters['surname'] = $parameters['surname'] ?? $individual->getAllNames()[0]['surn'] ?? null;
143            }
144        }
145
146        $parameters['tree'] = $tree->name();
147
148        return route(static::class, $parameters);
149    }
150
151    /**
152     * @return array<string>
153     */
154    public function listUrlAttributes(): array
155    {
156        return [];
157    }
158
159    /**
160     * Handle URLs generated by older versions of webtrees
161     *
162     * @param ServerRequestInterface $request
163     *
164     * @return ResponseInterface
165     */
166    public function getPageAction(ServerRequestInterface $request): ResponseInterface
167    {
168        $tree = Validator::attributes($request)->tree();
169
170        return redirect($this->listUrl($tree, $request->getQueryParams()));
171    }
172
173    /**
174     * @param ServerRequestInterface $request
175     *
176     * @return ResponseInterface
177     */
178    public function handle(ServerRequestInterface $request): ResponseInterface
179    {
180        $tree = Validator::attributes($request)->tree();
181        $user = Validator::attributes($request)->user();
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        = Validator::queryParams($request)->boolean('ajax', false);
194        $soundex_std = (bool) ($params['soundex_std'] ?? false);
195        $soundex_dm  = (bool) ($params['soundex_dm'] ?? false);
196
197        if ($ajax) {
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 !== PedigreeLinkageType::VALUE_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