xref: /webtrees/app/Module/IndividualListModule.php (revision dff81305056ece421b7a0cf2d2cfc5e08717a262)
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 Fisharebest\Localization\Locale\LocaleInterface;
23use Fisharebest\Webtrees\Auth;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\Family;
26use Fisharebest\Webtrees\I18N;
27use Fisharebest\Webtrees\Individual;
28use Fisharebest\Webtrees\Registry;
29use Fisharebest\Webtrees\Services\LocalizationService;
30use Fisharebest\Webtrees\Session;
31use Fisharebest\Webtrees\Tree;
32use Fisharebest\Webtrees\Validator;
33use Illuminate\Database\Capsule\Manager as DB;
34use Illuminate\Database\Query\Builder;
35use Illuminate\Database\Query\Expression;
36use Illuminate\Database\Query\JoinClause;
37use Illuminate\Support\Collection;
38use Psr\Http\Message\ResponseInterface;
39use Psr\Http\Message\ServerRequestInterface;
40use Psr\Http\Server\RequestHandlerInterface;
41
42use function app;
43use function array_keys;
44use function assert;
45use function e;
46use function implode;
47use function in_array;
48use function ob_get_clean;
49use function ob_start;
50use function redirect;
51use function route;
52use function view;
53
54/**
55 * Class IndividualListModule
56 */
57class IndividualListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
58{
59    use ModuleListTrait;
60
61    protected const ROUTE_URL = '/tree/{tree}/individual-list';
62
63    private LocalizationService $localization_service;
64
65    /**
66     * IndividualListModule constructor.
67     *
68     * @param LocalizationService $localization_service
69     */
70    public function __construct(LocalizationService $localization_service)
71    {
72        $this->localization_service = $localization_service;
73    }
74
75    /**
76     * Initialization.
77     *
78     * @return void
79     */
80    public function boot(): void
81    {
82        Registry::routeFactory()->routeMap()
83            ->get(static::class, static::ROUTE_URL, $this);
84    }
85
86    /**
87     * How should this module be identified in the control panel, etc.?
88     *
89     * @return string
90     */
91    public function title(): string
92    {
93        /* I18N: Name of a module/list */
94        return I18N::translate('Individuals');
95    }
96
97    /**
98     * A sentence describing what this module does.
99     *
100     * @return string
101     */
102    public function description(): string
103    {
104        /* I18N: Description of the “Individuals” module */
105        return I18N::translate('A list of individuals.');
106    }
107
108    /**
109     * CSS class for the URL.
110     *
111     * @return string
112     */
113    public function listMenuClass(): string
114    {
115        return 'menu-list-indi';
116    }
117
118    /**
119     * @param Tree                                      $tree
120     * @param array<bool|int|string|array<string>|null> $parameters
121     *
122     * @return string
123     */
124    public function listUrl(Tree $tree, array $parameters = []): string
125    {
126        $request = app(ServerRequestInterface::class);
127        assert($request instanceof ServerRequestInterface);
128
129        $xref = Validator::attributes($request)->isXref()->string('xref', '');
130
131        if ($xref !== '') {
132            $individual = Registry::individualFactory()->make($xref, $tree);
133
134            if ($individual instanceof Individual && $individual->canShow()) {
135                $primary_name = $individual->getPrimaryName();
136
137                $parameters['surname'] = $parameters['surname'] ?? $individual->getAllNames()[$primary_name]['surn'] ?? null;
138            }
139        }
140
141        $parameters['tree'] = $tree->name();
142
143        return route(static::class, $parameters);
144    }
145
146    /**
147     * @return array<string>
148     */
149    public function listUrlAttributes(): array
150    {
151        return [];
152    }
153
154    /**
155     * Handle URLs generated by older versions of webtrees
156     *
157     * @param ServerRequestInterface $request
158     *
159     * @return ResponseInterface
160     */
161    public function getListAction(ServerRequestInterface $request): ResponseInterface
162    {
163        $tree = Validator::attributes($request)->tree();
164
165        return redirect($this->listUrl($tree, $request->getQueryParams()));
166    }
167
168    /**
169     * @param ServerRequestInterface $request
170     *
171     * @return ResponseInterface
172     */
173    public function handle(ServerRequestInterface $request): ResponseInterface
174    {
175        $tree = Validator::attributes($request)->tree();
176        $user = Validator::attributes($request)->user();
177
178        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
179
180        return $this->createResponse($tree, $user, $request->getQueryParams(), false);
181    }
182
183    /**
184     * @param Tree          $tree
185     * @param UserInterface $user
186     * @param array<string> $params
187     * @param bool          $families
188     *
189     * @return ResponseInterface
190     */
191    protected function createResponse(Tree $tree, UserInterface $user, array $params, bool $families): ResponseInterface
192    {
193        ob_start();
194
195        // We show three different lists: initials, surnames and individuals
196
197        // All surnames beginning with this letter where "@"=unknown and ","=none
198        $alpha = $params['alpha'] ?? '';
199
200        // All individuals with this surname
201        $surname = $params['surname'] ?? '';
202
203        // All individuals
204        $show_all = $params['show_all'] ?? 'no';
205
206        // Long lists can be broken down by given name
207        $show_all_firstnames = $params['show_all_firstnames'] ?? 'no';
208        if ($show_all_firstnames === 'yes') {
209            $falpha = '';
210        } else {
211            // All first names beginning with this letter
212            $falpha = $params['falpha'] ?? '';
213        }
214
215        $show_marnm = $params['show_marnm'] ?? '';
216        switch ($show_marnm) {
217            case 'no':
218            case 'yes':
219                $user->setPreference($families ? 'family-list-marnm' : 'individual-list-marnm', $show_marnm);
220                break;
221            default:
222                $show_marnm = $user->getPreference($families ? 'family-list-marnm' : 'individual-list-marnm');
223        }
224
225        // Make sure selections are consistent.
226        // i.e. can’t specify show_all and surname at the same time.
227        if ($show_all === 'yes') {
228            $alpha   = '';
229            $surname = '';
230
231            if ($show_all_firstnames === 'yes') {
232                $legend  = I18N::translate('All');
233                $params  = [
234                    'tree'     => $tree->name(),
235                    'show_all' => 'yes',
236                ];
237                $show    = 'indi';
238            } elseif ($falpha !== '') {
239                $legend  = I18N::translate('All') . ', ' . e($falpha) . '…';
240                $params  = [
241                    'tree'     => $tree->name(),
242                    'show_all' => 'yes',
243                ];
244                $show    = 'indi';
245            } else {
246                $legend  = I18N::translate('All');
247                $show    = $params['show'] ?? 'surn';
248                $params  = [
249                    'tree'     => $tree->name(),
250                    'show_all' => 'yes',
251                ];
252            }
253        } elseif ($surname !== '') {
254            $alpha    = $this->localization_service->initialLetter($surname, I18N::locale()); // so we can highlight the initial letter
255            $show_all = 'no';
256            if ($surname === Individual::NOMEN_NESCIO) {
257                $legend = I18N::translateContext('Unknown surname', '…');
258            } else {
259                // The surname parameter is a root/canonical form.
260                // Display it as the actual surname
261                $legend = implode('/', array_keys($this->surnames($tree, $surname, $alpha, $show_marnm === 'yes', $families, I18N::locale())));
262            }
263            $params = [
264                'tree'    => $tree->name(),
265                'surname' => $surname,
266                'falpha'  => $falpha,
267            ];
268            switch ($falpha) {
269                case '':
270                    break;
271                case '@':
272                    $legend .= ', ' . I18N::translateContext('Unknown given name', '…');
273                    break;
274                default:
275                    $legend .= ', ' . e($falpha) . '…';
276                    break;
277            }
278            $show = 'indi'; // SURN list makes no sense here
279        } elseif ($alpha === '@') {
280            $show_all = 'no';
281            $legend   = I18N::translateContext('Unknown surname', '…');
282            $params   = [
283                'alpha' => $alpha,
284                'tree'  => $tree->name(),
285            ];
286            $show     = 'indi'; // SURN list makes no sense here
287        } elseif ($alpha === ',') {
288            $show_all = 'no';
289            $legend   = I18N::translate('No surname');
290            $params   = [
291                'alpha' => $alpha,
292                'tree'  => $tree->name(),
293            ];
294            $show     = 'indi'; // SURN list makes no sense here
295        } elseif ($alpha !== '') {
296            $show_all = 'no';
297            $legend   = e($alpha) . '…';
298            $show     = $params['show'] ?? 'surn';
299            $params   = [
300                'alpha' => $alpha,
301                'tree'  => $tree->name(),
302            ];
303        } else {
304            $show_all = 'no';
305            $legend   = '…';
306            $params   = [
307                'tree' => $tree->name(),
308            ];
309            $show     = 'none'; // Don't show lists until something is chosen
310        }
311        $legend = '<bdi>' . $legend . '</bdi>';
312
313        if ($families) {
314            $title = I18N::translate('Families') . ' — ' . $legend;
315        } else {
316            $title = I18N::translate('Individuals') . ' — ' . $legend;
317        } ?>
318        <div class="d-flex flex-column wt-page-options wt-page-options-individual-list d-print-none">
319            <ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-surname">
320
321                <?php foreach ($this->surnameAlpha($tree, $show_marnm === 'yes', $families, I18N::locale()) as $letter => $count) : ?>
322                    <li class="wt-initials-list-item d-flex">
323                        <?php if ($count > 0) : ?>
324                            <a href="<?= e($this->listUrl($tree, ['alpha' => $letter, 'tree' => $tree->name()])) ?>" class="wt-initial px-1<?= $letter === $alpha ? ' active' : '' ?> '" title="<?= I18N::number($count) ?>"><?= $this->surnameInitial((string) $letter) ?></a>
325                        <?php else : ?>
326                            <span class="wt-initial px-1 text-muted"><?= $this->surnameInitial((string) $letter) ?></span>
327
328                        <?php endif ?>
329                    </li>
330                <?php endforeach ?>
331
332                <?php if (Session::has('initiated')) : ?>
333                    <!-- Search spiders don't get the "show all" option as the other links give them everything. -->
334                    <li class="wt-initials-list-item d-flex">
335                        <a class="wt-initial px-1<?= $show_all === 'yes' ? ' active' : '' ?>" href="<?= e($this->listUrl($tree, ['show_all' => 'yes'] + $params)) ?>"><?= I18N::translate('All') ?></a>
336                    </li>
337                <?php endif ?>
338            </ul>
339
340            <!-- Search spiders don't get an option to show/hide the surname sublists, nor does it make sense on the all/unknown/surname views -->
341            <?php if ($show !== 'none' && Session::has('initiated')) : ?>
342                <?php if ($show_marnm === 'yes') : ?>
343                    <p>
344                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'no'] + $params)) ?>">
345                            <?= I18N::translate('Exclude individuals with “%s” as a married name', $legend) ?>
346                        </a>
347                    </p>
348                <?php else : ?>
349                    <p>
350                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'yes'] + $params)) ?>">
351                            <?= I18N::translate('Include individuals with “%s” as a married name', $legend) ?>
352                        </a>
353                    </p>
354                <?php endif ?>
355
356                <?php if ($alpha !== '@' && $alpha !== ',' && $surname === '') : ?>
357                    <?php if ($show === 'surn') : ?>
358                        <p>
359                            <a href="<?= e($this->listUrl($tree, ['show' => 'indi', 'show_marnm' => 'no'] + $params)) ?>">
360                                <?= I18N::translate('Show the list of individuals') ?>
361                            </a>
362                        </p>
363                    <?php else : ?>
364                        <p>
365                            <a href="<?= e($this->listUrl($tree, ['show' => 'surn', 'show_marnm' => 'no'] + $params)) ?>">
366                                <?= I18N::translate('Show the list of surnames') ?>
367                            </a>
368                        </p>
369                    <?php endif ?>
370                <?php endif ?>
371            <?php endif ?>
372        </div>
373
374        <div class="wt-page-content">
375            <?php
376
377            if ($show === 'indi' || $show === 'surn') {
378                $surns = $this->surnames($tree, $surname, $alpha, $show_marnm === 'yes', $families, I18N::locale());
379                if ($show === 'surn') {
380                    // Show the surname list
381                    switch ($tree->getPreference('SURNAME_LIST_STYLE')) {
382                        case 'style1':
383                            echo view('lists/surnames-column-list', [
384                                'module'   => $this,
385                                'surnames' => $surns,
386                                'totals'   => true,
387                                'tree'     => $tree,
388                            ]);
389                            break;
390                        case 'style3':
391                            echo view('lists/surnames-tag-cloud', [
392                                'module'   => $this,
393                                'surnames' => $surns,
394                                'totals'   => true,
395                                'tree'     => $tree,
396                            ]);
397                            break;
398                        case 'style2':
399                        default:
400                            echo view('lists/surnames-table', [
401                                'families' => $families,
402                                'module'   => $this,
403                                'order'    => [[1, 'desc']],
404                                'surnames' => $surns,
405                                'tree'     => $tree,
406                            ]);
407                            break;
408                    }
409                } else {
410                    // Show the list
411                    $count = 0;
412                    foreach ($surns as $surnames) {
413                        foreach ($surnames as $total) {
414                            $count += $total;
415                        }
416                    }
417                    // Don't sublist short lists.
418                    if ($count < $tree->getPreference('SUBLIST_TRIGGER_I')) {
419                        $falpha = '';
420                    } else {
421                        $givn_initials = $this->givenAlpha($tree, $surname, $alpha, $show_marnm === 'yes', $families, I18N::locale());
422                        // Break long lists by initial letter of given name
423                        if ($surname !== '' || $show_all === 'yes') {
424                            if ($show_all === 'no') {
425                                echo '<h2 class="wt-page-title">', I18N::translate('Individuals with surname %s', $legend), '</h2>';
426                            }
427                            // Don't show the list until we have some filter criteria
428                            $show = $falpha !== '' || $show_all_firstnames === 'yes' ? 'indi' : 'none';
429                            $list = [];
430                            echo '<ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-given-names">';
431                            foreach ($givn_initials as $givn_initial => $given_count) {
432                                echo '<li class="wt-initials-list-item d-flex">';
433                                if ($given_count > 0) {
434                                    if ($show === 'indi' && $givn_initial === $falpha && $show_all_firstnames === 'no') {
435                                        echo '<a class="wt-initial px-1 active" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->givenNameInitial((string) $givn_initial) . '</a>';
436                                    } else {
437                                        echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->givenNameInitial((string) $givn_initial) . '</a>';
438                                    }
439                                } else {
440                                    echo '<span class="wt-initial px-1 text-muted">' . $this->givenNameInitial((string) $givn_initial) . '</span>';
441                                }
442                                echo '</li>';
443                            }
444                            // Search spiders don't get the "show all" option as the other links give them everything.
445                            if (Session::has('initiated')) {
446                                echo '<li class="wt-initials-list-item d-flex">';
447                                if ($show_all_firstnames === 'yes') {
448                                    echo '<span class="wt-initial px-1 active">' . I18N::translate('All') . '</span>';
449                                } else {
450                                    echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['show_all_firstnames' => 'yes'] + $params)) . '" title="' . I18N::number($count) . '">' . I18N::translate('All') . '</a>';
451                                }
452                                echo '</li>';
453                            }
454                            echo '</ul>';
455                            echo '<p class="text-center alpha_index">', implode(' | ', $list), '</p>';
456                        }
457                    }
458                    if ($show === 'indi') {
459                        if (!$families) {
460                            echo view('lists/individuals-table', [
461                                'individuals' => $this->individuals($tree, $surname, $alpha, $falpha, $show_marnm === 'yes', false, I18N::locale()),
462                                'sosa'        => false,
463                                'tree'        => $tree,
464                            ]);
465                        } else {
466                            echo view('lists/families-table', [
467                                'families' => $this->families($tree, $surname, $alpha, $falpha, $show_marnm === 'yes', I18N::locale()),
468                                'tree'     => $tree,
469                            ]);
470                        }
471                    }
472                }
473            } ?>
474        </div>
475        <?php
476
477        $html = ob_get_clean();
478
479        return $this->viewResponse('modules/individual-list/page', [
480            'content' => $html,
481            'title'   => $title,
482            'tree'    => $tree,
483        ]);
484    }
485
486    /**
487     * Some initial letters have a special meaning
488     *
489     * @param string $initial
490     *
491     * @return string
492     */
493    protected function givenNameInitial(string $initial): string
494    {
495        if ($initial === '@') {
496            return I18N::translateContext('Unknown given name', '…');
497        }
498
499        return e($initial);
500    }
501
502    /**
503     * Some initial letters have a special meaning
504     *
505     * @param string $initial
506     *
507     * @return string
508     */
509    protected function surnameInitial(string $initial): string
510    {
511        if ($initial === '@') {
512            return I18N::translateContext('Unknown surname', '…');
513        }
514
515        if ($initial === ',') {
516            return I18N::translate('No surname');
517        }
518
519        return e($initial);
520    }
521
522    /**
523     * Restrict a query to individuals that are a spouse in a family record.
524     *
525     * @param bool    $fams
526     * @param Builder $query
527     */
528    protected function whereFamily(bool $fams, Builder $query): void
529    {
530        if ($fams) {
531            $query->join('link', static function (JoinClause $join): void {
532                $join
533                    ->on('l_from', '=', 'n_id')
534                    ->on('l_file', '=', 'n_file')
535                    ->where('l_type', '=', 'FAMS');
536            });
537        }
538    }
539
540    /**
541     * Restrict a query to include/exclude married names.
542     *
543     * @param bool    $marnm
544     * @param Builder $query
545     */
546    protected function whereMarriedName(bool $marnm, Builder $query): void
547    {
548        if (!$marnm) {
549            $query->where('n_type', '<>', '_MARNM');
550        }
551    }
552
553    /**
554     * Get a list of initial surname letters.
555     *
556     * @param Tree            $tree
557     * @param bool            $marnm if set, include married names
558     * @param bool            $fams  if set, only consider individuals with FAMS records
559     * @param LocaleInterface $locale
560     *
561     * @return array<int>
562     */
563    public function surnameAlpha(Tree $tree, bool $marnm, bool $fams, LocaleInterface $locale): array
564    {
565        $collation = $this->localization_service->collation($locale);
566
567        $n_surn = $this->fieldWithCollation('n_surn', $collation);
568        $alphas = [];
569
570        $query = DB::table('name')->where('n_file', '=', $tree->id());
571
572        $this->whereFamily($fams, $query);
573        $this->whereMarriedName($marnm, $query);
574
575        // Fetch all the letters in our alphabet, whether or not there
576        // are any names beginning with that letter. It looks better to
577        // show the full alphabet, rather than omitting rare letters such as X.
578        foreach ($this->localization_service->alphabet($locale) as $letter) {
579            $query2 = clone $query;
580
581            $this->whereInitial($query2, 'n_surn', $letter, $locale);
582
583            $alphas[$letter] = $query2->count();
584        }
585
586        // Now fetch initial letters that are not in our alphabet,
587        // including "@" (for "@N.N.") and "" for no surname.
588        foreach ($this->localization_service->alphabet($locale) as $letter) {
589            $query->where($n_surn, 'NOT LIKE', $letter . '%');
590        }
591
592        $rows = $query
593            ->groupBy(['initial'])
594            ->orderBy('initial')
595            ->pluck(new Expression('COUNT(*) AS aggregate'), new Expression('SUBSTR(n_surn, 1, 1) AS initial'));
596
597        $specials = ['@', ''];
598
599        foreach ($rows as $alpha => $count) {
600            if (!in_array($alpha, $specials, true)) {
601                $alphas[$alpha] = (int) $count;
602            }
603        }
604
605        // Empty surnames have a special code ',' - as we search for SURN,GIVN
606        foreach ($specials as $special) {
607            if ($rows->has($special)) {
608                $alphas[$special ?: ','] = (int) $rows[$special];
609            }
610        }
611
612        return $alphas;
613    }
614
615    /**
616     * Get a list of initial given name letters for indilist.php and famlist.php
617     *
618     * @param Tree            $tree
619     * @param string          $surn   if set, only consider people with this surname
620     * @param string          $salpha if set, only consider surnames starting with this letter
621     * @param bool            $marnm  if set, include married names
622     * @param bool            $fams   if set, only consider individuals with FAMS records
623     * @param LocaleInterface $locale
624     *
625     * @return array<int>
626     */
627    public function givenAlpha(Tree $tree, string $surn, string $salpha, bool $marnm, bool $fams, LocaleInterface $locale): array
628    {
629        $collation = $this->localization_service->collation($locale);
630
631        $alphas = [];
632
633        $query = DB::table('name')
634            ->where('n_file', '=', $tree->id());
635
636        $this->whereFamily($fams, $query);
637        $this->whereMarriedName($marnm, $query);
638
639        if ($surn !== '') {
640            $n_surn = $this->fieldWithCollation('n_surn', $collation);
641            $query->where($n_surn, '=', $surn);
642        } elseif ($salpha === ',') {
643            $query->where('n_surn', '=', '');
644        } elseif ($salpha === '@') {
645            $query->where('n_surn', '=', Individual::NOMEN_NESCIO);
646        } elseif ($salpha !== '') {
647            $this->whereInitial($query, 'n_surn', $salpha, $locale);
648        } else {
649            // All surnames
650            $query->whereNotIn('n_surn', ['', Individual::NOMEN_NESCIO]);
651        }
652
653        // Fetch all the letters in our alphabet, whether or not there
654        // are any names beginning with that letter. It looks better to
655        // show the full alphabet, rather than omitting rare letters such as X
656        foreach ($this->localization_service->alphabet($locale) as $letter) {
657            $query2 = clone $query;
658
659            $this->whereInitial($query2, 'n_givn', $letter, $locale);
660
661            $alphas[$letter] = $query2->distinct()->count('n_id');
662        }
663
664        $rows = $query
665            ->groupBy(['initial'])
666            ->orderBy('initial')
667            ->pluck(new Expression('COUNT(*) AS aggregate'), new Expression('UPPER(SUBSTR(n_givn, 1, 1)) AS initial'));
668
669        foreach ($rows as $alpha => $count) {
670            if ($alpha !== '@') {
671                $alphas[$alpha] = (int) $count;
672            }
673        }
674
675        if ($rows->has('@')) {
676            $alphas['@'] = (int) $rows['@'];
677        }
678
679        return $alphas;
680    }
681
682    /**
683     * Get a count of actual surnames and variants, based on a "root" surname.
684     *
685     * @param Tree            $tree
686     * @param string          $surn   if set, only count people with this surname
687     * @param string          $salpha if set, only consider surnames starting with this letter
688     * @param bool            $marnm  if set, include married names
689     * @param bool            $fams   if set, only consider individuals with FAMS records
690     * @param LocaleInterface $locale
691     *
692     * @return array<array<int>>
693     */
694    protected function surnames(
695        Tree $tree,
696        string $surn,
697        string $salpha,
698        bool $marnm,
699        bool $fams,
700        LocaleInterface $locale
701    ): array {
702        $query = DB::table('name')
703            ->where('n_file', '=', $tree->id())
704            ->select([
705                new Expression('n_surn /*! COLLATE utf8_bin */ AS n_surn'),
706                new Expression('n_surname /*! COLLATE utf8_bin */ AS n_surname'),
707                new Expression('COUNT(*) AS total'),
708            ]);
709
710        $this->whereFamily($fams, $query);
711        $this->whereMarriedName($marnm, $query);
712
713        if ($surn !== '') {
714            $query->where('n_surn', '=', $surn);
715        } elseif ($salpha === ',') {
716            $query->where('n_surn', '=', '');
717        } elseif ($salpha === '@') {
718            $query->where('n_surn', '=', Individual::NOMEN_NESCIO);
719        } elseif ($salpha !== '') {
720            $this->whereInitial($query, 'n_surn', $salpha, $locale);
721        } else {
722            // All surnames
723            $query->whereNotIn('n_surn', ['', Individual::NOMEN_NESCIO]);
724        }
725        $query->groupBy([
726            new Expression('n_surn /*! COLLATE utf8_bin */'),
727            new Expression('n_surname /*! COLLATE utf8_bin */'),
728        ]);
729
730        $list = [];
731
732        foreach ($query->get() as $row) {
733            $row->n_surn = I18N::strtoupper($row->n_surn);
734            $row->total += $list[$row->n_surn][$row->n_surname] ?? 0;
735
736            $list[$row->n_surn][$row->n_surname] = (int) $row->total;
737        }
738
739        uksort($list, I18N::comparator());
740
741        return $list;
742    }
743
744    /**
745     * Fetch a list of individuals with specified names
746     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
747     * To search for names with no surnames, use $salpha=","
748     *
749     * @param Tree            $tree
750     * @param string          $surn   if set, only fetch people with this surname
751     * @param string          $salpha if set, only fetch surnames starting with this letter
752     * @param string          $galpha if set, only fetch given names starting with this letter
753     * @param bool            $marnm  if set, include married names
754     * @param bool            $fams   if set, only fetch individuals with FAMS records
755     * @param LocaleInterface $locale
756     *
757     * @return Collection<Individual>
758     */
759    protected function individuals(
760        Tree $tree,
761        string $surn,
762        string $salpha,
763        string $galpha,
764        bool $marnm,
765        bool $fams,
766        LocaleInterface $locale
767    ): Collection {
768        $collation = $this->localization_service->collation($locale);
769
770        // Use specific collation for name fields.
771        $n_givn = $this->fieldWithCollation('n_givn', $collation);
772        $n_surn = $this->fieldWithCollation('n_surn', $collation);
773
774        $query = DB::table('individuals')
775            ->join('name', static function (JoinClause $join): void {
776                $join
777                    ->on('n_id', '=', 'i_id')
778                    ->on('n_file', '=', 'i_file');
779            })
780            ->where('i_file', '=', $tree->id())
781            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'n_givn', 'n_surn']);
782
783        $this->whereFamily($fams, $query);
784        $this->whereMarriedName($marnm, $query);
785
786        if ($surn) {
787            $query->where($n_surn, '=', $surn);
788        } elseif ($salpha === ',') {
789            $query->where($n_surn, '=', '');
790        } elseif ($salpha === '@') {
791            $query->where($n_surn, '=', Individual::NOMEN_NESCIO);
792        } elseif ($salpha) {
793            $this->whereInitial($query, 'n_surn', $salpha, $locale);
794        } else {
795            // All surnames
796            $query->whereNotIn($n_surn, ['', Individual::NOMEN_NESCIO]);
797        }
798        if ($galpha) {
799            $this->whereInitial($query, 'n_givn', $galpha, $locale);
800        }
801
802        $query
803            ->orderBy(new Expression("CASE n_surn WHEN '" . Individual::NOMEN_NESCIO . "' THEN 1 ELSE 0 END"))
804            ->orderBy($n_surn)
805            ->orderBy(new Expression("CASE n_givn WHEN '" . Individual::NOMEN_NESCIO . "' THEN 1 ELSE 0 END"))
806            ->orderBy($n_givn);
807
808        $individuals = new Collection();
809        $rows = $query->get();
810
811        foreach ($rows as $row) {
812            $individual = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
813            assert($individual instanceof Individual);
814
815            // The name from the database may be private - check the filtered list...
816            foreach ($individual->getAllNames() as $n => $name) {
817                if ($name['givn'] === $row->n_givn && $name['surn'] === $row->n_surn) {
818                    $individual->setPrimaryName($n);
819                    // We need to clone $individual, as we may have multiple references to the
820                    // same individual in this list, and the "primary name" would otherwise
821                    // be shared amongst all of them.
822                    $individuals->push(clone $individual);
823                    break;
824                }
825            }
826        }
827
828        return $individuals;
829    }
830
831    /**
832     * Fetch a list of families with specified names
833     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
834     * To search for names with no surnames, use $salpha=","
835     *
836     * @param Tree            $tree
837     * @param string          $surn   if set, only fetch people with this surname
838     * @param string          $salpha if set, only fetch surnames starting with this letter
839     * @param string          $galpha if set, only fetch given names starting with this letter
840     * @param bool            $marnm  if set, include married names
841     * @param LocaleInterface $locale
842     *
843     * @return Collection<Family>
844     */
845    protected function families(Tree $tree, string $surn, string $salpha, string $galpha, bool $marnm, LocaleInterface $locale): Collection
846    {
847        $families = new Collection();
848
849        foreach ($this->individuals($tree, $surn, $salpha, $galpha, $marnm, true, $locale) as $indi) {
850            foreach ($indi->spouseFamilies() as $family) {
851                $families->push($family);
852            }
853        }
854
855        return $families->unique();
856    }
857
858    /**
859     * Use MySQL-specific comments so we can run these queries on other RDBMS.
860     *
861     * @param string $field
862     * @param string $collation
863     *
864     * @return Expression
865     */
866    protected function fieldWithCollation(string $field, string $collation): Expression
867    {
868        return new Expression($field . ' /*! COLLATE ' . $collation . ' */');
869    }
870
871    /**
872     * Modify a query to restrict a field to a given initial letter.
873     * Take account of digraphs, equialent letters, etc.
874     *
875     * @param Builder         $query
876     * @param string          $field
877     * @param string          $letter
878     * @param LocaleInterface $locale
879     *
880     * @return void
881     */
882    protected function whereInitial(
883        Builder $query,
884        string $field,
885        string $letter,
886        LocaleInterface $locale
887    ): void {
888        $collation = $this->localization_service->collation($locale);
889
890        // Use MySQL-specific comments so we can run these queries on other RDBMS.
891        $field_with_collation = $this->fieldWithCollation($field, $collation);
892
893        switch ($locale->languageTag()) {
894            case 'cs':
895                $this->whereInitialCzech($query, $field_with_collation, $letter);
896                break;
897
898            case 'da':
899            case 'nb':
900            case 'nn':
901                $this->whereInitialNorwegian($query, $field_with_collation, $letter);
902                break;
903
904            case 'sv':
905            case 'fi':
906                $this->whereInitialSwedish($query, $field_with_collation, $letter);
907                break;
908
909            case 'hu':
910                $this->whereInitialHungarian($query, $field_with_collation, $letter);
911                break;
912
913            case 'nl':
914                $this->whereInitialDutch($query, $field_with_collation, $letter);
915                break;
916
917            default:
918                $query->where($field_with_collation, 'LIKE', '\\' . $letter . '%');
919        }
920    }
921
922    /**
923     * @param Builder    $query
924     * @param Expression $field
925     * @param string     $letter
926     */
927    protected function whereInitialCzech(Builder $query, Expression $field, string $letter): void
928    {
929        if ($letter === 'C') {
930            $query->where($field, 'LIKE', 'C%')->where($field, 'NOT LIKE', 'CH%');
931        } else {
932            $query->where($field, 'LIKE', '\\' . $letter . '%');
933        }
934    }
935
936    /**
937     * @param Builder    $query
938     * @param Expression $field
939     * @param string     $letter
940     */
941    protected function whereInitialDutch(Builder $query, Expression $field, string $letter): void
942    {
943        if ($letter === 'I') {
944            $query->where($field, 'LIKE', 'I%')->where($field, 'NOT LIKE', 'IJ%');
945        } else {
946            $query->where($field, 'LIKE', '\\' . $letter . '%');
947        }
948    }
949
950    /**
951     * Hungarian has many digraphs and trigraphs, so exclude these from prefixes.
952     *
953     * @param Builder    $query
954     * @param Expression $field
955     * @param string     $letter
956     */
957    protected function whereInitialHungarian(Builder $query, Expression $field, string $letter): void
958    {
959        switch ($letter) {
960            case 'C':
961                $query->where($field, 'LIKE', 'C%')->where($field, 'NOT LIKE', 'CS%');
962                break;
963
964            case 'D':
965                $query->where($field, 'LIKE', 'D%')->where($field, 'NOT LIKE', 'DZ%');
966                break;
967
968            case 'DZ':
969                $query->where($field, 'LIKE', 'DZ%')->where($field, 'NOT LIKE', 'DZS%');
970                break;
971
972            case 'G':
973                $query->where($field, 'LIKE', 'G%')->where($field, 'NOT LIKE', 'GY%');
974                break;
975
976            case 'L':
977                $query->where($field, 'LIKE', 'L%')->where($field, 'NOT LIKE', 'LY%');
978                break;
979
980            case 'N':
981                $query->where($field, 'LIKE', 'N%')->where($field, 'NOT LIKE', 'NY%');
982                break;
983
984            case 'S':
985                $query->where($field, 'LIKE', 'S%')->where($field, 'NOT LIKE', 'SZ%');
986                break;
987
988            case 'T':
989                $query->where($field, 'LIKE', 'T%')->where($field, 'NOT LIKE', 'TY%');
990                break;
991
992            case 'Z':
993                $query->where($field, 'LIKE', 'Z%')->where($field, 'NOT LIKE', 'ZS%');
994                break;
995
996            default:
997                $query->where($field, 'LIKE', '\\' . $letter . '%');
998                break;
999        }
1000    }
1001
1002    /**
1003     * In Norwegian and Danish, AA gets listed under Å, NOT A
1004     *
1005     * @param Builder    $query
1006     * @param Expression $field
1007     * @param string     $letter
1008     */
1009    protected function whereInitialNorwegian(Builder $query, Expression $field, string $letter): void
1010    {
1011        switch ($letter) {
1012            case 'A':
1013                $query->where($field, 'LIKE', 'A%')->where($field, 'NOT LIKE', 'AA%');
1014                break;
1015
1016            case 'Å':
1017                $query->where(static function (Builder $query) use ($field): void {
1018                    $query
1019                        ->where($field, 'LIKE', 'Å%')
1020                        ->orWhere($field, 'LIKE', 'AA%');
1021                });
1022                break;
1023
1024            default:
1025                $query->where($field, 'LIKE', '\\' . $letter . '%');
1026                break;
1027        }
1028    }
1029
1030    /**
1031     * In Swedish and Finnish, AA gets listed under A, NOT Å (even though Swedish collation says they should).
1032     *
1033     * @param Builder    $query
1034     * @param Expression $field
1035     * @param string     $letter
1036     */
1037    protected function whereInitialSwedish(Builder $query, Expression $field, string $letter): void
1038    {
1039        if ($letter === 'Å') {
1040            $query->where($field, 'LIKE', 'Å%')->where($field, 'NOT LIKE', 'AA%');
1041        } else {
1042            $query->where($field, 'LIKE', '\\' . $letter . '%');
1043        }
1044    }
1045}
1046