Passed
Push — develop ( a7f908...8b59ed )
by Greg
10:03 queued 03:38
created

IndividualListModule::givenNameInitials()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 21
c 1
b 0
f 0
nc 16
nop 4
dl 0
loc 37
rs 9.2728
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
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Module;
21
22
use Fisharebest\Webtrees\Auth;
23
use Fisharebest\Webtrees\Contracts\UserInterface;
24
use Fisharebest\Webtrees\Family;
25
use Fisharebest\Webtrees\I18N;
26
use Fisharebest\Webtrees\Individual;
27
use Fisharebest\Webtrees\Registry;
28
use Fisharebest\Webtrees\Session;
29
use Fisharebest\Webtrees\Tree;
30
use Fisharebest\Webtrees\Validator;
31
use Illuminate\Database\Capsule\Manager as DB;
32
use Illuminate\Database\Query\Builder;
33
use Illuminate\Database\Query\Expression;
34
use Illuminate\Database\Query\JoinClause;
35
use Illuminate\Support\Collection;
36
use Psr\Http\Message\ResponseInterface;
37
use Psr\Http\Message\ServerRequestInterface;
38
use Psr\Http\Server\RequestHandlerInterface;
39
40
use function app;
41
use function array_filter;
42
use function array_keys;
43
use function array_sum;
44
use function assert;
45
use function e;
46
use function implode;
47
use function ob_get_clean;
48
use function ob_start;
49
use function route;
50
use function uksort;
51
use function var_dump;
52
use function view;
53
54
use const ARRAY_FILTER_USE_KEY;
55
56
/**
57
 * Class IndividualListModule
58
 */
59
class IndividualListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
60
{
61
    use ModuleListTrait;
62
63
    protected const ROUTE_URL = '/tree/{tree}/individual-list';
64
65
    /**
66
     * Initialization.
67
     *
68
     * @return void
69
     */
70
    public function boot(): void
71
    {
72
        Registry::routeFactory()->routeMap()
73
            ->get(static::class, static::ROUTE_URL, $this);
74
    }
75
76
    /**
77
     * How should this module be identified in the control panel, etc.?
78
     *
79
     * @return string
80
     */
81
    public function title(): string
82
    {
83
        /* I18N: Name of a module/list */
84
        return I18N::translate('Individuals');
85
    }
86
87
    /**
88
     * A sentence describing what this module does.
89
     *
90
     * @return string
91
     */
92
    public function description(): string
93
    {
94
        /* I18N: Description of the “Individuals” module */
95
        return I18N::translate('A list of individuals.');
96
    }
97
98
    /**
99
     * CSS class for the URL.
100
     *
101
     * @return string
102
     */
103
    public function listMenuClass(): string
104
    {
105
        return 'menu-list-indi';
106
    }
107
108
    /**
109
     * @param Tree                                      $tree
110
     * @param array<bool|int|string|array<string>|null> $parameters
111
     *
112
     * @return string
113
     */
114
    public function listUrl(Tree $tree, array $parameters = []): string
115
    {
116
        $request = app(ServerRequestInterface::class);
117
        assert($request instanceof ServerRequestInterface);
118
119
        $xref = Validator::attributes($request)->isXref()->string('xref', '');
120
121
        if ($xref !== '') {
122
            $individual = Registry::individualFactory()->make($xref, $tree);
123
124
            if ($individual instanceof Individual && $individual->canShow()) {
125
                $primary_name = $individual->getPrimaryName();
126
127
                $parameters['surname'] = $parameters['surname'] ?? $individual->getAllNames()[$primary_name]['surn'] ?? null;
128
            }
129
        }
130
131
        $parameters['tree'] = $tree->name();
132
133
        return route(static::class, $parameters);
134
    }
135
136
    /**
137
     * @return array<string>
138
     */
139
    public function listUrlAttributes(): array
140
    {
141
        return [];
142
    }
143
144
    /**
145
     * @param ServerRequestInterface $request
146
     *
147
     * @return ResponseInterface
148
     */
149
    public function handle(ServerRequestInterface $request): ResponseInterface
150
    {
151
        $tree = Validator::attributes($request)->tree();
152
        $user = Validator::attributes($request)->user();
153
154
        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
155
156
        $surname_param = Validator::queryParams($request)->string('surname', '');
157
        $surname       = I18N::strtoupper(I18N::language()->normalize($surname_param));
158
159
        $params = [
160
            'alpha'               => Validator::queryParams($request)->string('alpha', ''),
161
            'falpha'              => Validator::queryParams($request)->string('falpha', ''),
162
            'show'                => Validator::queryParams($request)->string('show', 'surn'),
163
            'show_all'            => Validator::queryParams($request)->string('show_all', 'no'),
164
            'show_all_firstnames' => Validator::queryParams($request)->string('show_all_firstnames', 'no'),
165
            'show_marnm'          => Validator::queryParams($request)->string('show_marnm', ''),
166
            'surname'             => $surname,
167
        ];
168
169
        if ($surname_param !== $surname) {
170
            return Registry::responseFactory()->redirectUrl($this->listUrl($tree, $params));
171
        }
172
173
        return $this->createResponse($tree, $user, $params, false);
174
    }
175
176
    /**
177
     * @param Tree          $tree
178
     * @param UserInterface $user
179
     * @param array<string> $params
180
     * @param bool          $families
181
     *
182
     * @return ResponseInterface
183
     */
184
    protected function createResponse(Tree $tree, UserInterface $user, array $params, bool $families): ResponseInterface
185
    {
186
        ob_start();
187
188
        // We show three different lists: initials, surnames and individuals
189
190
        // All surnames beginning with this letter, where "@" is unknown and "," is none
191
        $alpha = $params['alpha'];
192
193
        // All individuals with this surname
194
        $surname = $params['surname'];
195
196
        // All individuals
197
        $show_all = $params['show_all'] === 'yes';
198
199
        // Include/exclude married names
200
        $show_marnm = $params['show_marnm'];
201
202
        // What type of list to display, if any
203
        $show = $params['show'];
204
205
        // Break long lists down by given name
206
        $show_all_firstnames = $params['show_all_firstnames'] === 'yes';
207
208
        // All first names beginning with this letter where "@" is unknown
209
        $falpha = $params['falpha'];
210
211
        // Make sure parameters are consistent with each other.
212
        if ($show_all_firstnames) {
213
            $falpha = '';
214
        }
215
216
        if ($show_all) {
217
            $alpha   = '';
218
            $surname = '';
219
        }
220
221
        if ($surname !== '') {
222
            $alpha = I18N::language()->initialLetter($surname);
223
        }
224
225
        $all_surnames     = $this->allSurnames($tree, $show_marnm === 'yes', $families);
226
        $surname_initials = $this->surnameInitials($all_surnames);
227
228
        switch ($show_marnm) {
229
            case 'no':
230
            case 'yes':
231
                $user->setPreference($families ? 'family-list-marnm' : 'individual-list-marnm', $show_marnm);
232
                break;
233
            default:
234
                $show_marnm = $user->getPreference($families ? 'family-list-marnm' : 'individual-list-marnm');
235
        }
236
237
        // Make sure selections are consistent.
238
        // i.e. can’t specify show_all and surname at the same time.
239
        if ($show_all) {
240
            if ($show_all_firstnames) {
241
                $legend  = I18N::translate('All');
242
                $params = ['tree' => $tree->name(), 'show_all' => 'yes'];
243
                $show    = 'indi';
244
            } elseif ($falpha !== '') {
245
                $legend  = I18N::translate('All') . ', ' . e($falpha) . '…';
246
                $params = ['tree' => $tree->name(), 'show_all' => 'yes'];
247
                $show    = 'indi';
248
            } else {
249
                $legend  = I18N::translate('All');
250
                $params = ['tree' => $tree->name(), 'show_all' => 'yes'];
251
            }
252
        } elseif ($surname !== '') {
253
            $show_all = false;
254
            if ($surname === Individual::NOMEN_NESCIO) {
255
                $legend = I18N::translateContext('Unknown surname', '…');
256
                if (count($all_surnames[$surname]) === 1) {
257
                    //$show = 'indi'; // The surname list makes no sense with only one surname.
258
                }
259
            } else {
260
                // The surname parameter is a root/canonical form.
261
                // Display the actual surnames found.
262
                $variants = array_keys($all_surnames[$surname]);
263
                usort($variants, I18N::comparator());
264
                $variants = array_map(static fn (string $x): string => $x === '' ? I18N::translate('No surname') : $x, $variants);
265
                $legend   = implode('/', $variants);
266
                $show     = 'indi'; // The surname list makes no sense with only one surname.
267
            }
268
            $params = ['tree' => $tree->name(), 'surname' => $surname, 'falpha' => $falpha];
269
            switch ($falpha) {
270
                case '':
271
                    break;
272
                case '@':
273
                    $legend .= ', ' . I18N::translateContext('Unknown given name', '…');
274
                    break;
275
                default:
276
                    $legend .= ', ' . e($falpha) . '…';
277
                    break;
278
            }
279
        } elseif ($alpha === '@') {
280
            $show_all = false;
281
            $legend   = I18N::translateContext('Unknown surname', '…');
282
            $params   = ['alpha' => $alpha, 'tree' => $tree->name()];
283
            $surname  = Individual::NOMEN_NESCIO;
284
            $show     = 'indi'; // SURN list makes no sense here
285
        } elseif ($alpha === ',') {
286
            $show_all = false;
287
            $legend   = I18N::translate('No surname');
288
            $params = ['alpha' => $alpha, 'tree' => $tree->name()];
289
            $show     = 'indi'; // SURN list makes no sense here
290
        } elseif ($alpha !== '') {
291
            $show_all = false;
292
            $legend   = e($alpha) . '…';
293
            $params = ['alpha' => $alpha, 'tree' => $tree->name()];
294
        } else {
295
            $show_all = false;
296
            $legend   = '…';
297
            $params   = ['tree' => $tree->name()];
298
            $show     = 'none'; // Don't show lists until something is chosen
299
        }
300
        $legend = '<bdi>' . $legend . '</bdi>';
301
302
        if ($families) {
303
            $title = I18N::translate('Families') . ' — ' . $legend;
304
        } else {
305
            $title = I18N::translate('Individuals') . ' — ' . $legend;
306
        }
307
308
        ?>
309
        <div class="d-flex flex-column wt-page-options wt-page-options-individual-list d-print-none">
310
            <ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-surname">
311
312
                <?php foreach ($surname_initials as $letter => $count) : ?>
313
                    <li class="wt-initials-list-item d-flex">
314
                        <?php if ($count > 0) : ?>
315
                            <a href="<?= e($this->listUrl($tree, ['alpha' => $letter, 'tree' => $tree->name()])) ?>" class="wt-initial px-1<?= $letter === $alpha ? ' active' : '' ?> '" title="<?= I18N::number($count) ?>"><?= $this->displaySurnameInitial((string) $letter) ?></a>
316
                        <?php else : ?>
317
                            <span class="wt-initial px-1 text-muted"><?= $this->displaySurnameInitial((string) $letter) ?></span>
318
319
                        <?php endif ?>
320
                    </li>
321
                <?php endforeach ?>
322
323
                <?php if (Session::has('initiated')) : ?>
324
                    <!-- Search spiders don't get the "show all" option as the other links give them everything. -->
325
                    <li class="wt-initials-list-item d-flex">
326
                        <a class="wt-initial px-1<?= $show_all ? ' active' : '' ?>" href="<?= e($this->listUrl($tree, ['show_all' => 'yes'] + $params)) ?>"><?= I18N::translate('All') ?></a>
327
                    </li>
328
                <?php endif ?>
329
            </ul>
330
331
            <!-- Search spiders don't get an option to show/hide the surname sublists, nor does it make sense on the all/unknown/surname views -->
332
            <?php if ($show !== 'none' && Session::has('initiated')) : ?>
333
                <?php if ($show_marnm === 'yes') : ?>
334
                    <p>
335
                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'no'] + $params)) ?>">
336
                            <?= I18N::translate('Exclude individuals with “%s” as a married name', $legend) ?>
337
                        </a>
338
                    </p>
339
                <?php else : ?>
340
                    <p>
341
                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'yes'] + $params)) ?>">
342
                            <?= I18N::translate('Include individuals with “%s” as a married name', $legend) ?>
343
                        </a>
344
                    </p>
345
                <?php endif ?>
346
347
                <?php if ($alpha !== '@' && $alpha !== ',' && $surname === '') : ?>
348
                    <?php if ($show === 'surn') : ?>
349
                        <p>
350
                            <a href="<?= e($this->listUrl($tree, ['show' => 'indi', 'show_marnm' => 'no'] + $params)) ?>">
351
                                <?= I18N::translate('Show the list of individuals') ?>
352
                            </a>
353
                        </p>
354
                    <?php else : ?>
355
                        <p>
356
                            <a href="<?= e($this->listUrl($tree, ['show' => 'surn', 'show_marnm' => 'no'] + $params)) ?>">
357
                                <?= I18N::translate('Show the list of surnames') ?>
358
                            </a>
359
                        </p>
360
                    <?php endif ?>
361
                <?php endif ?>
362
            <?php endif ?>
363
        </div>
364
365
        <div class="wt-page-content">
366
            <?php
367
            if ($show === 'indi' || $show === 'surn') {
368
                switch ($alpha) {
369
                    case '@':
370
                        $surns = array_filter($all_surnames, static fn (string $x): bool => $x === Individual::NOMEN_NESCIO, ARRAY_FILTER_USE_KEY);
371
                        break;
372
                    case ',':
373
                        $surns = array_filter($all_surnames, static fn (string $x): bool => $x === '', ARRAY_FILTER_USE_KEY);
374
                        break;
375
                    case '':
376
                        if ($show_all) {
377
                            $surns = array_filter($all_surnames, static fn (string $x): bool => $x !== '' && $x !== Individual::NOMEN_NESCIO, ARRAY_FILTER_USE_KEY);
378
                        } else {
379
                            $surns = array_filter($all_surnames, static fn (string $x): bool => $x === $surname, ARRAY_FILTER_USE_KEY);
380
                        }
381
                        break;
382
                    default:
383
                        if ($surname === '') {
384
                            $surns = array_filter($all_surnames, static fn (string $x): bool => I18N::language()->initialLetter($x) === $alpha, ARRAY_FILTER_USE_KEY);
385
                        } else {
386
                            $surns = array_filter($all_surnames, static fn (string $x): bool => $x === $surname, ARRAY_FILTER_USE_KEY);
387
                        }
388
                        break;
389
                }
390
391
                if ($show === 'surn') {
392
                    // Show the surname list
393
                    switch ($tree->getPreference('SURNAME_LIST_STYLE')) {
394
                        case 'style1':
395
                            echo view('lists/surnames-column-list', [
396
                                'module'   => $this,
397
                                'surnames' => $surns,
398
                                'totals'   => true,
399
                                'tree'     => $tree,
400
                            ]);
401
                            break;
402
                        case 'style3':
403
                            echo view('lists/surnames-tag-cloud', [
404
                                'module'   => $this,
405
                                'surnames' => $surns,
406
                                'totals'   => true,
407
                                'tree'     => $tree,
408
                            ]);
409
                            break;
410
                        case 'style2':
411
                        default:
412
                            echo view('lists/surnames-table', [
413
                                'families' => $families,
414
                                'module'   => $this,
415
                                'order'    => [[0, 'asc']],
416
                                'surnames' => $surns,
417
                                'tree'     => $tree,
418
                            ]);
419
                            break;
420
                    }
421
                } else {
422
                    // Show the list
423
                    $count = array_sum(array_map(static fn (array $x): int => array_sum($x), $surns));
424
425
                    // Don't sublist short lists.
426
                    if ($count < $tree->getPreference('SUBLIST_TRIGGER_I')) {
427
                        $falpha = '';
428
                    } else {
429
                        $givn_initials = $this->givenNameInitials($tree, array_keys($surns), $show_marnm === 'yes', $families);
430
                        // Break long lists by initial letter of given name
431
                        if ($surname !== '' || $show_all) {
432
                            if (!$show_all) {
433
                                echo '<h2 class="wt-page-title">', I18N::translate('Individuals with surname %s', $legend), '</h2>';
434
                            }
435
                            // Don't show the list until we have some filter criteria
436
                            $show = $falpha !== '' || $show_all_firstnames ? 'indi' : 'none';
437
                            echo '<ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-given-names">';
438
                            foreach ($givn_initials as $givn_initial => $given_count) {
439
                                echo '<li class="wt-initials-list-item d-flex">';
440
                                if ($given_count > 0) {
441
                                    if ($show === 'indi' && $givn_initial === $falpha && !$show_all_firstnames) {
442
                                        echo '<a class="wt-initial px-1 active" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->displayGivenNameInitial((string) $givn_initial) . '</a>';
443
                                    } else {
444
                                        echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->displayGivenNameInitial((string) $givn_initial) . '</a>';
445
                                    }
446
                                } else {
447
                                    echo '<span class="wt-initial px-1 text-muted">' . $this->displayGivenNameInitial((string) $givn_initial) . '</span>';
448
                                }
449
                                echo '</li>';
450
                            }
451
                            // Search spiders don't get the "show all" option as the other links give them everything.
452
                            if (Session::has('initiated')) {
453
                                echo '<li class="wt-initials-list-item d-flex">';
454
                                if ($show_all_firstnames) {
455
                                    echo '<span class="wt-initial px-1 active">' . I18N::translate('All') . '</span>';
456
                                } else {
457
                                    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>';
458
                                }
459
                                echo '</li>';
460
                            }
461
                            echo '</ul>';
462
                        }
463
                    }
464
                    if ($show === 'indi') {
465
                        if ($families) {
466
                            echo view('lists/families-table', [
467
                                'families' => $this->families($tree, $surname, array_keys($all_surnames[$surname] ?? []), $falpha, $show_marnm === 'yes'),
468
                                'tree'     => $tree,
469
                            ]);
470
                        } else {
471
                            echo view('lists/individuals-table', [
472
                                'individuals' => $this->individuals($tree, $surname, array_keys($all_surnames[$surname] ?? []), $falpha, $show_marnm === 'yes', false),
473
                                'sosa'        => false,
474
                                'tree'        => $tree,
475
                            ]);
476
                        }
477
                    }
478
                }
479
            } ?>
480
        </div>
481
        <?php
482
483
        $html = ob_get_clean();
484
485
        return $this->viewResponse('modules/individual-list/page', [
486
            'content' => $html,
487
            'title'   => $title,
488
            'tree'    => $tree,
489
        ]);
490
    }
491
492
    /**
493
     * Some initial letters have a special meaning
494
     *
495
     * @param string $initial
496
     *
497
     * @return string
498
     */
499
    protected function displayGivenNameInitial(string $initial): string
500
    {
501
        if ($initial === '@') {
502
            return I18N::translateContext('Unknown given name', '…');
503
        }
504
505
        return e($initial);
506
    }
507
508
    /**
509
     * Some initial letters have a special meaning
510
     *
511
     * @param string $initial
512
     *
513
     * @return string
514
     */
515
    protected function displaySurnameInitial(string $initial): string
516
    {
517
        if ($initial === '@') {
518
            return I18N::translateContext('Unknown surname', '…');
519
        }
520
521
        if ($initial === ',') {
522
            return I18N::translate('No surname');
523
        }
524
525
        return e($initial);
526
    }
527
528
    /**
529
     * Restrict a query to individuals that are a spouse in a family record.
530
     *
531
     * @param bool    $fams
532
     * @param Builder $query
533
     */
534
    protected function whereFamily(bool $fams, Builder $query): void
535
    {
536
        if ($fams) {
537
            $query->join('link', static function (JoinClause $join): void {
538
                $join
539
                    ->on('l_from', '=', 'n_id')
540
                    ->on('l_file', '=', 'n_file')
541
                    ->where('l_type', '=', 'FAMS');
542
            });
543
        }
544
    }
545
546
    /**
547
     * Restrict a query to include/exclude married names.
548
     *
549
     * @param bool    $marnm
550
     * @param Builder $query
551
     */
552
    protected function whereMarriedName(bool $marnm, Builder $query): void
553
    {
554
        if (!$marnm) {
555
            $query->where('n_type', '<>', '_MARNM');
556
        }
557
    }
558
559
    /**
560
     * Get a count of individuals with each initial letter
561
     *
562
     * @param Tree          $tree
563
     * @param array<string> $surns if set, only consider people with this surname
564
     * @param bool          $marnm if set, include married names
565
     * @param bool          $fams  if set, only consider individuals with FAMS records
566
     *
567
     * @return array<int>
568
     */
569
    public function givenNameInitials(Tree $tree, array $surns, bool $marnm, bool $fams): array
570
    {
571
        $initials = [];
572
573
        // Ensure our own language comes before others.
574
        foreach (I18N::language()->alphabet() as $initial) {
575
            $initials[$initial] = 0;
576
        }
577
578
        $query = DB::table('name')
579
            ->where('n_file', '=', $tree->id());
580
581
        $this->whereFamily($fams, $query);
582
        $this->whereMarriedName($marnm, $query);
583
584
        if ($surns !== []) {
585
            $query->whereIn('n_surn', $surns);
586
        }
587
588
        $query
589
            ->select($this->binaryColumn('n_givn', 'n_givn'), new Expression('COUNT(*) AS count'))
590
            ->groupBy([$this->binaryColumn('n_givn')]);
591
592
        foreach ($query->get() as $row) {
593
            $initial = I18N::strtoupper(I18N::language()->initialLetter($row->n_givn));
594
            $initials[$initial] ??= 0;
595
            $initials[$initial] += (int) $row->count;
596
        }
597
598
        $count_unknown = $initials['@'] ?? 0;
599
600
        if ($count_unknown > 0) {
601
            unset($initials['@']);
602
            $initials['@'] = $count_unknown;
603
        }
604
605
        return $initials;
606
    }
607
608
    /**
609
     * Get a count of all surnames and variants.
610
     *
611
     * @param Tree $tree
612
     * @param bool $marnm if set, include married names
613
     * @param bool $fams  if set, only consider individuals with FAMS records
614
     *
615
     * @return array<array<int>>
616
     */
617
    protected function allSurnames(Tree $tree, bool $marnm, bool $fams): array
618
    {
619
        $query = DB::table('name')
620
            ->where('n_file', '=', $tree->id())
621
            ->select([
622
                $this->binaryColumn('n_surn', 'n_surn'),
623
                $this->binaryColumn('n_surname', 'n_surname'),
624
                new Expression('COUNT(*) AS total'),
625
            ]);
626
627
        $this->whereFamily($fams, $query);
628
        $this->whereMarriedName($marnm, $query);
629
630
        $query->groupBy([
631
            $this->binaryColumn('n_surn'),
632
            $this->binaryColumn('n_surname'),
633
        ]);
634
635
        /** @var array<array<int>> $list */
636
        $list = [];
637
638
        foreach ($query->get() as $row) {
639
            // Some users wrongly set SURN without a surname in NAME.
640
            $row->n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
641
642
            // Ignore upper/lower case and most diacritics when grouping names.
643
            $row->n_surn = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
644
645
            $list[$row->n_surn][$row->n_surname] ??= 0;
646
            $list[$row->n_surn][$row->n_surname] += (int) $row->total;
647
        }
648
649
        uksort($list, I18N::comparator());
650
651
        return $list;
652
    }
653
654
    /**
655
     * Extract initial letters and counts for all surnames.
656
     *
657
     * @param array<array<int>> $all_surnames
658
     *
659
     * @return array<int>
660
     */
661
    protected function surnameInitials(array $all_surnames): array
662
    {
663
        $initials    = [];
664
665
        // Ensure our own language comes before others.
666
        foreach (I18N::language()->alphabet() as $initial) {
667
            $initials[$initial]    = 0;
668
        }
669
670
        foreach ($all_surnames as $surn => $surnames) {
671
            $initial = I18N::language()->initialLetter($surn);
672
673
            $initials[$initial] ??= 0;
674
            $initials[$initial] += array_sum($surnames);
675
        }
676
677
        // Move specials to the end
678
        $count_none = $initials[''] ?? 0;
679
680
        if ($count_none > 0) {
681
            unset($initials['']);
682
            $initials[','] = $count_none;
683
        }
684
685
        $count_unknown = $initials['@'] ?? 0;
686
687
        if ($count_unknown > 0) {
688
            unset($initials['@']);
689
            $initials['@'] = $count_unknown;
690
        }
691
692
        return $initials;
693
    }
694
695
    /**
696
     * Fetch a list of individuals with specified names
697
     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
698
     * To search for names with no surnames, use $salpha=","
699
     *
700
     * @param Tree            $tree
701
     * @param string          $surname  if set, only fetch people with this n_surn
702
     * @param array<string>   $surnames if set, only fetch people with this n_surname
703
     * @param string          $galpha   if set, only fetch given names starting with this letter
704
     * @param bool            $marnm    if set, include married names
705
     * @param bool            $fams     if set, only fetch individuals with FAMS records
706
     *
707
     * @return Collection<int,Individual>
708
     */
709
    protected function individuals(Tree $tree, string $surname, array $surnames, string $galpha, bool $marnm, bool $fams): Collection
710
    {
711
        $query = DB::table('individuals')
712
            ->join('name', static function (JoinClause $join): void {
713
                $join
714
                    ->on('n_id', '=', 'i_id')
715
                    ->on('n_file', '=', 'i_file');
716
            })
717
            ->where('i_file', '=', $tree->id())
718
            ->where('n_surn', '=', $surname)
719
            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'n_givn', 'n_surn']);
720
721
        $this->whereFamily($fams, $query);
722
        $this->whereMarriedName($marnm, $query);
723
724
        if ($surnames !== []) {
725
            $query->whereIn($this->binaryColumn('n_surname'), $surnames);
726
        }
727
728
        $query
729
            ->orderBy(new Expression("CASE n_surn WHEN '" . Individual::NOMEN_NESCIO . "' THEN 1 ELSE 0 END"))
730
            ->orderBy('n_surn')
731
            ->orderBy(new Expression("CASE n_givn WHEN '" . Individual::NOMEN_NESCIO . "' THEN 1 ELSE 0 END"))
732
            ->orderBy('n_givn');
733
734
        $individuals = new Collection();
735
736
        $rows = $query->get();
737
738
        foreach ($rows as $row) {
739
            $individual = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
740
            assert($individual instanceof Individual);
741
742
            // The name from the database may be private - check the filtered list...
743
            foreach ($individual->getAllNames() as $n => $name) {
744
                if ($name['givn'] === $row->n_givn && $name['surn'] === $row->n_surn) {
745
                    if ($galpha === '' || I18N::strtoupper(I18N::language()->initialLetter($row->n_givn)) === $galpha) {
746
                        $individual->setPrimaryName($n);
747
                        // We need to clone $individual, as we may have multiple references to the
748
                        // same individual in this list, and the "primary name" would otherwise
749
                        // be shared amongst all of them.
750
                        $individuals->push(clone $individual);
751
                        break;
752
                    }
753
                }
754
            }
755
        }
756
757
        return $individuals;
758
    }
759
760
    /**
761
     * Fetch a list of families with specified names
762
     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
763
     * To search for names with no surnames, use $salpha=","
764
     *
765
     * @param Tree          $tree
766
     * @param string        $surname  if set, only fetch people with this n_surn
767
     * @param array<string> $surnames if set, only fetch people with this n_surname
768
     * @param string        $galpha   if set, only fetch given names starting with this letter
769
     * @param bool          $marnm    if set, include married names
770
     *
771
     * @return Collection<int,Family>
772
     */
773
    protected function families(Tree $tree, string $surname, array $surnames, string $galpha, bool $marnm): Collection
774
    {
775
        $families = new Collection();
776
777
        foreach ($this->individuals($tree, $surname, $surnames, $galpha, $marnm, true) as $indi) {
778
            foreach ($indi->spouseFamilies() as $family) {
779
                $families->push($family);
780
            }
781
        }
782
783
        return $families->unique();
784
    }
785
786
    /**
787
     * This module assumes the database will use binary collation on the name columns.
788
     * Until we convert MySQL databases to use utf8_bin, we need to do this at run-time.
789
     *
790
     * @param string      $column
791
     * @param string|null $alias
792
     *
793
     * @return Expression
794
     */
795
    private function binaryColumn(string $column, string $alias = null): Expression
796
    {
797
        if (DB::connection()->getDriverName() === 'mysql') {
798
            $sql = 'CAST(' . $column . ' AS binary)';
799
        } else {
800
            $sql = $column;
801
        }
802
803
        if ($alias !== null) {
804
            $sql .= ' AS ' . $alias;
805
        }
806
807
        return new Expression($sql);
808
    }
809
}
810