xref: /webtrees/app/Services/SearchService.php (revision 5bfc689774bb9a6401271c4ed15a6d50652c991b)
132cd2800SGreg Roach<?php
23976b470SGreg Roach
332cd2800SGreg Roach/**
432cd2800SGreg Roach * webtrees: online genealogy
5*5bfc6897SGreg Roach * Copyright (C) 2022 webtrees development team
632cd2800SGreg Roach * This program is free software: you can redistribute it and/or modify
732cd2800SGreg Roach * it under the terms of the GNU General Public License as published by
832cd2800SGreg Roach * the Free Software Foundation, either version 3 of the License, or
932cd2800SGreg Roach * (at your option) any later version.
1032cd2800SGreg Roach * This program is distributed in the hope that it will be useful,
1132cd2800SGreg Roach * but WITHOUT ANY WARRANTY; without even the implied warranty of
1232cd2800SGreg Roach * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1332cd2800SGreg Roach * GNU General Public License for more details.
1432cd2800SGreg Roach * You should have received a copy of the GNU General Public License
1589f7189bSGreg Roach * along with this program. If not, see <https://www.gnu.org/licenses/>.
1632cd2800SGreg Roach */
17fcfa147eSGreg Roach
1832cd2800SGreg Roachdeclare(strict_types=1);
1932cd2800SGreg Roach
2032cd2800SGreg Roachnamespace Fisharebest\Webtrees\Services;
2132cd2800SGreg Roach
2232cd2800SGreg Roachuse Closure;
23dfb2cda2SGreg Roachuse Fisharebest\Webtrees\Date;
2432cd2800SGreg Roachuse Fisharebest\Webtrees\Family;
25a7a24840SGreg Roachuse Fisharebest\Webtrees\Gedcom;
2632cd2800SGreg Roachuse Fisharebest\Webtrees\GedcomRecord;
2781b729d3SGreg Roachuse Fisharebest\Webtrees\Http\Exceptions\HttpServiceUnavailableException;
2852a8ef61SGreg Roachuse Fisharebest\Webtrees\I18N;
2932cd2800SGreg Roachuse Fisharebest\Webtrees\Individual;
3081b729d3SGreg Roachuse Fisharebest\Webtrees\Location;
3132cd2800SGreg Roachuse Fisharebest\Webtrees\Media;
3232cd2800SGreg Roachuse Fisharebest\Webtrees\Note;
33b68caec6SGreg Roachuse Fisharebest\Webtrees\Place;
3481b729d3SGreg Roachuse Fisharebest\Webtrees\Registry;
3532cd2800SGreg Roachuse Fisharebest\Webtrees\Repository;
362d686e68SGreg Roachuse Fisharebest\Webtrees\Soundex;
3732cd2800SGreg Roachuse Fisharebest\Webtrees\Source;
38d4ac8227SGreg Roachuse Fisharebest\Webtrees\Submission;
39b5c8fd7eSGreg Roachuse Fisharebest\Webtrees\Submitter;
4032cd2800SGreg Roachuse Fisharebest\Webtrees\Tree;
4132cd2800SGreg Roachuse Illuminate\Database\Capsule\Manager as DB;
4232cd2800SGreg Roachuse Illuminate\Database\Query\Builder;
43a7a24840SGreg Roachuse Illuminate\Database\Query\Expression;
4432cd2800SGreg Roachuse Illuminate\Database\Query\JoinClause;
4532cd2800SGreg Roachuse Illuminate\Support\Collection;
463976b470SGreg Roach
47b5961194SGreg Roachuse function addcslashes;
48b4adec9eSGreg Roachuse function array_filter;
49b4adec9eSGreg Roachuse function array_map;
5056946b7aSGreg Roachuse function array_unique;
5156946b7aSGreg Roachuse function explode;
52b4adec9eSGreg Roachuse function implode;
53a7a24840SGreg Roachuse function mb_stripos;
54b4adec9eSGreg Roachuse function preg_match;
55b4adec9eSGreg Roachuse function preg_quote;
56b4adec9eSGreg Roachuse function preg_replace;
572f86083cSGreg Roachuse function str_ends_with;
582f86083cSGreg Roachuse function str_starts_with;
592f86083cSGreg Roach
60b4adec9eSGreg Roachuse const PHP_INT_MAX;
6132cd2800SGreg Roach
6232cd2800SGreg Roach/**
6332cd2800SGreg Roach * Search trees for genealogy records.
6432cd2800SGreg Roach */
6532cd2800SGreg Roachclass SearchService
6632cd2800SGreg Roach{
67645e3037SGreg Roach    // Do not attempt to show search results larger than this/
68645e3037SGreg Roach    protected const MAX_SEARCH_RESULTS = 5000;
69645e3037SGreg Roach
70c4943cffSGreg Roach    private TreeService $tree_service;
71d5ad3db0SGreg Roach
72d5ad3db0SGreg Roach    /**
73d5ad3db0SGreg Roach     * SearchService constructor.
74d5ad3db0SGreg Roach     *
75d5ad3db0SGreg Roach     * @param TreeService $tree_service
76d5ad3db0SGreg Roach     */
773959eeb6SGreg Roach    public function __construct(
783959eeb6SGreg Roach        TreeService $tree_service
793959eeb6SGreg Roach    ) {
80d5ad3db0SGreg Roach        $this->tree_service = $tree_service;
81d5ad3db0SGreg Roach    }
82d5ad3db0SGreg Roach
83a7a24840SGreg Roach    /**
8409482a55SGreg Roach     * @param array<Tree>   $trees
8509482a55SGreg Roach     * @param array<string> $search
86a7a24840SGreg Roach     *
8736779af1SGreg Roach     * @return Collection<int,Family>
88a7a24840SGreg Roach     */
89a7a24840SGreg Roach    public function searchFamilies(array $trees, array $search): Collection
90a7a24840SGreg Roach    {
91a7a24840SGreg Roach        $query = DB::table('families');
92a7a24840SGreg Roach
93a7a24840SGreg Roach        $this->whereTrees($query, 'f_file', $trees);
94a7a24840SGreg Roach        $this->whereSearch($query, 'f_gedcom', $search);
95a7a24840SGreg Roach
96a7a24840SGreg Roach        return $query
97a7a24840SGreg Roach            ->get()
9852a8ef61SGreg Roach            ->each($this->rowLimiter())
99d5ad3db0SGreg Roach            ->map($this->familyRowMapper())
100a7a24840SGreg Roach            ->filter(GedcomRecord::accessFilter())
1017f5fa3c2SGreg Roach            ->filter($this->rawGedcomFilter($search));
102a7a24840SGreg Roach    }
103a7a24840SGreg Roach
10432cd2800SGreg Roach    /**
10532cd2800SGreg Roach     * Search for families by name.
10632cd2800SGreg Roach     *
10709482a55SGreg Roach     * @param array<Tree>   $trees
10809482a55SGreg Roach     * @param array<string> $search
10932cd2800SGreg Roach     * @param int           $offset
11032cd2800SGreg Roach     * @param int           $limit
11132cd2800SGreg Roach     *
11236779af1SGreg Roach     * @return Collection<int,Family>
11332cd2800SGreg Roach     */
114a7a24840SGreg Roach    public function searchFamilyNames(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
11532cd2800SGreg Roach    {
11632cd2800SGreg Roach        $query = DB::table('families')
117ac499332SGreg Roach            ->leftJoin('name AS husb_name', static function (JoinClause $join): void {
11832cd2800SGreg Roach                $join
11932cd2800SGreg Roach                    ->on('husb_name.n_file', '=', 'families.f_file')
120ac499332SGreg Roach                    ->on('husb_name.n_id', '=', 'families.f_husb')
121ac499332SGreg Roach                    ->where('husb_name.n_type', '<>', '_MARNM');
12232cd2800SGreg Roach            })
123ac499332SGreg Roach            ->leftJoin('name AS wife_name', static function (JoinClause $join): void {
12432cd2800SGreg Roach                $join
12532cd2800SGreg Roach                    ->on('wife_name.n_file', '=', 'families.f_file')
126ac499332SGreg Roach                    ->on('wife_name.n_id', '=', 'families.f_wife')
127ac499332SGreg Roach                    ->where('wife_name.n_type', '<>', '_MARNM');
128ac499332SGreg Roach            });
129a7a24840SGreg Roach
130a7a24840SGreg Roach        $prefix = DB::connection()->getTablePrefix();
131a69f5655SGreg Roach        $field  = new Expression('COALESCE(' . $prefix . "husb_name.n_full, '') || COALESCE(" . $prefix . "wife_name.n_full, '')");
132a7a24840SGreg Roach
133a7a24840SGreg Roach        $this->whereTrees($query, 'f_file', $trees);
134a7a24840SGreg Roach        $this->whereSearch($query, $field, $search);
135a7a24840SGreg Roach
136a7a24840SGreg Roach        $query
13732cd2800SGreg Roach            ->orderBy('husb_name.n_sort')
13832cd2800SGreg Roach            ->orderBy('wife_name.n_sort')
1398aaf5f58SGreg Roach            ->select(['families.*', 'husb_name.n_sort', 'wife_name.n_sort']);
14032cd2800SGreg Roach
141d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->familyRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
142a7a24840SGreg Roach    }
143a7a24840SGreg Roach
144a7a24840SGreg Roach    /**
145dbe53437SGreg Roach     * @param Place $place
146dbe53437SGreg Roach     *
14736779af1SGreg Roach     * @return Collection<int,Family>
148dbe53437SGreg Roach     */
149dbe53437SGreg Roach    public function searchFamiliesInPlace(Place $place): Collection
150dbe53437SGreg Roach    {
151dbe53437SGreg Roach        return DB::table('families')
152dbe53437SGreg Roach            ->join('placelinks', static function (JoinClause $query) {
153dbe53437SGreg Roach                $query
154dbe53437SGreg Roach                    ->on('families.f_file', '=', 'placelinks.pl_file')
155dbe53437SGreg Roach                    ->on('families.f_id', '=', 'placelinks.pl_gid');
156dbe53437SGreg Roach            })
157dbe53437SGreg Roach            ->where('f_file', '=', $place->tree()->id())
158dbe53437SGreg Roach            ->where('pl_p_id', '=', $place->id())
159dbe53437SGreg Roach            ->select(['families.*'])
160dbe53437SGreg Roach            ->get()
161dbe53437SGreg Roach            ->each($this->rowLimiter())
162dbe53437SGreg Roach            ->map($this->familyRowMapper())
163dbe53437SGreg Roach            ->filter(GedcomRecord::accessFilter());
164dbe53437SGreg Roach    }
165dbe53437SGreg Roach
166dbe53437SGreg Roach    /**
16709482a55SGreg Roach     * @param array<Tree>   $trees
16809482a55SGreg Roach     * @param array<string> $search
169a7a24840SGreg Roach     *
17036779af1SGreg Roach     * @return Collection<int,Individual>
171a7a24840SGreg Roach     */
172a7a24840SGreg Roach    public function searchIndividuals(array $trees, array $search): Collection
173a7a24840SGreg Roach    {
174a7a24840SGreg Roach        $query = DB::table('individuals');
175a7a24840SGreg Roach
176a7a24840SGreg Roach        $this->whereTrees($query, 'i_file', $trees);
177a7a24840SGreg Roach        $this->whereSearch($query, 'i_gedcom', $search);
178a7a24840SGreg Roach
179a7a24840SGreg Roach        return $query
180a7a24840SGreg Roach            ->get()
18152a8ef61SGreg Roach            ->each($this->rowLimiter())
182d5ad3db0SGreg Roach            ->map($this->individualRowMapper())
183a7a24840SGreg Roach            ->filter(GedcomRecord::accessFilter())
1847f5fa3c2SGreg Roach            ->filter($this->rawGedcomFilter($search));
18532cd2800SGreg Roach    }
18632cd2800SGreg Roach
18732cd2800SGreg Roach    /**
18832cd2800SGreg Roach     * Search for individuals by name.
18932cd2800SGreg Roach     *
19009482a55SGreg Roach     * @param array<Tree>   $trees
19109482a55SGreg Roach     * @param array<string> $search
19232cd2800SGreg Roach     * @param int           $offset
19332cd2800SGreg Roach     * @param int           $limit
19432cd2800SGreg Roach     *
19536779af1SGreg Roach     * @return Collection<int,Individual>
19632cd2800SGreg Roach     */
197a7a24840SGreg Roach    public function searchIndividualNames(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
19832cd2800SGreg Roach    {
19932cd2800SGreg Roach        $query = DB::table('individuals')
2000b5fd0a6SGreg Roach            ->join('name', static function (JoinClause $join): void {
20132cd2800SGreg Roach                $join
20232cd2800SGreg Roach                    ->on('name.n_file', '=', 'individuals.i_file')
203a7a24840SGreg Roach                    ->on('name.n_id', '=', 'individuals.i_id');
20432cd2800SGreg Roach            })
205e84cf2deSGreg Roach            ->orderBy('n_sort')
206685de081SGreg Roach            ->select(['individuals.*', 'n_sort']);
20732cd2800SGreg Roach
208a7a24840SGreg Roach        $this->whereTrees($query, 'i_file', $trees);
209a7a24840SGreg Roach        $this->whereSearch($query, 'n_full', $search);
210a7a24840SGreg Roach
211d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->individualRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
21232cd2800SGreg Roach    }
21332cd2800SGreg Roach
21432cd2800SGreg Roach    /**
215dbe53437SGreg Roach     * @param Place $place
216dbe53437SGreg Roach     *
21736779af1SGreg Roach     * @return Collection<int,Individual>
218dbe53437SGreg Roach     */
219dbe53437SGreg Roach    public function searchIndividualsInPlace(Place $place): Collection
220dbe53437SGreg Roach    {
221dbe53437SGreg Roach        return DB::table('individuals')
222dbe53437SGreg Roach            ->join('placelinks', static function (JoinClause $join) {
223dbe53437SGreg Roach                $join
224dbe53437SGreg Roach                    ->on('i_file', '=', 'pl_file')
225dbe53437SGreg Roach                    ->on('i_id', '=', 'pl_gid');
226dbe53437SGreg Roach            })
227dbe53437SGreg Roach            ->where('i_file', '=', $place->tree()->id())
228dbe53437SGreg Roach            ->where('pl_p_id', '=', $place->id())
229dbe53437SGreg Roach            ->select(['individuals.*'])
230dbe53437SGreg Roach            ->get()
231dbe53437SGreg Roach            ->each($this->rowLimiter())
232dbe53437SGreg Roach            ->map($this->individualRowMapper())
233dbe53437SGreg Roach            ->filter(GedcomRecord::accessFilter());
234dbe53437SGreg Roach    }
235dbe53437SGreg Roach
236dbe53437SGreg Roach    /**
237d4ac8227SGreg Roach     * Search for submissions.
238d4ac8227SGreg Roach     *
23909482a55SGreg Roach     * @param array<Tree>   $trees
24009482a55SGreg Roach     * @param array<string> $search
241d4ac8227SGreg Roach     * @param int           $offset
242d4ac8227SGreg Roach     * @param int           $limit
243d4ac8227SGreg Roach     *
24436779af1SGreg Roach     * @return Collection<int,Location>
245d4ac8227SGreg Roach     */
246d4ac8227SGreg Roach    public function searchLocations(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
247d4ac8227SGreg Roach    {
248d4ac8227SGreg Roach        $query = DB::table('other')
249058ba724SGreg Roach            ->where('o_type', '=', Location::RECORD_TYPE);
250d4ac8227SGreg Roach
251d4ac8227SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
252d4ac8227SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
253d4ac8227SGreg Roach
254d4ac8227SGreg Roach        return $this->paginateQuery($query, $this->locationRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
255d4ac8227SGreg Roach    }
256d4ac8227SGreg Roach
257d4ac8227SGreg Roach    /**
25832cd2800SGreg Roach     * Search for media objects.
25932cd2800SGreg Roach     *
26009482a55SGreg Roach     * @param array<Tree>   $trees
26109482a55SGreg Roach     * @param array<string> $search
26232cd2800SGreg Roach     * @param int           $offset
26332cd2800SGreg Roach     * @param int           $limit
26432cd2800SGreg Roach     *
26536779af1SGreg Roach     * @return Collection<int,Media>
26632cd2800SGreg Roach     */
267a7a24840SGreg Roach    public function searchMedia(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
26832cd2800SGreg Roach    {
269a7a24840SGreg Roach        $query = DB::table('media');
27032cd2800SGreg Roach
271a7a24840SGreg Roach        $this->whereTrees($query, 'media.m_file', $trees);
272a7a24840SGreg Roach        $this->whereSearch($query, 'm_gedcom', $search);
273a7a24840SGreg Roach
274d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->mediaRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
27532cd2800SGreg Roach    }
27632cd2800SGreg Roach
27732cd2800SGreg Roach    /**
27832cd2800SGreg Roach     * Search for notes.
27932cd2800SGreg Roach     *
28009482a55SGreg Roach     * @param array<Tree>   $trees
28109482a55SGreg Roach     * @param array<string> $search
28232cd2800SGreg Roach     * @param int           $offset
28332cd2800SGreg Roach     * @param int           $limit
28432cd2800SGreg Roach     *
28536779af1SGreg Roach     * @return Collection<int,Note>
28632cd2800SGreg Roach     */
287a7a24840SGreg Roach    public function searchNotes(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
28832cd2800SGreg Roach    {
28932cd2800SGreg Roach        $query = DB::table('other')
290058ba724SGreg Roach            ->where('o_type', '=', Note::RECORD_TYPE);
29132cd2800SGreg Roach
292a7a24840SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
293a7a24840SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
294a7a24840SGreg Roach
295d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->noteRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
29632cd2800SGreg Roach    }
29732cd2800SGreg Roach
29832cd2800SGreg Roach    /**
29932cd2800SGreg Roach     * Search for repositories.
30032cd2800SGreg Roach     *
30109482a55SGreg Roach     * @param array<Tree>   $trees
30209482a55SGreg Roach     * @param array<string> $search
30332cd2800SGreg Roach     * @param int           $offset
30432cd2800SGreg Roach     * @param int           $limit
30532cd2800SGreg Roach     *
30636779af1SGreg Roach     * @return Collection<int,Repository>
30732cd2800SGreg Roach     */
308a7a24840SGreg Roach    public function searchRepositories(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
30932cd2800SGreg Roach    {
31032cd2800SGreg Roach        $query = DB::table('other')
311058ba724SGreg Roach            ->where('o_type', '=', Repository::RECORD_TYPE);
31232cd2800SGreg Roach
313a7a24840SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
314a7a24840SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
315a7a24840SGreg Roach
316d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->repositoryRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
31732cd2800SGreg Roach    }
31832cd2800SGreg Roach
31932cd2800SGreg Roach    /**
320a7a24840SGreg Roach     * Search for sources.
32132cd2800SGreg Roach     *
32209482a55SGreg Roach     * @param array<Tree>   $trees
32309482a55SGreg Roach     * @param array<string> $search
32432cd2800SGreg Roach     * @param int      $offset
32532cd2800SGreg Roach     * @param int      $limit
32632cd2800SGreg Roach     *
32736779af1SGreg Roach     * @return Collection<int,Source>
32832cd2800SGreg Roach     */
329a7a24840SGreg Roach    public function searchSources(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
330a7a24840SGreg Roach    {
331a7a24840SGreg Roach        $query = DB::table('sources');
332a7a24840SGreg Roach
333a7a24840SGreg Roach        $this->whereTrees($query, 's_file', $trees);
334a7a24840SGreg Roach        $this->whereSearch($query, 's_gedcom', $search);
335a7a24840SGreg Roach
336d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->sourceRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
337a7a24840SGreg Roach    }
338a7a24840SGreg Roach
339a7a24840SGreg Roach    /**
340a7a24840SGreg Roach     * Search for sources by name.
341a7a24840SGreg Roach     *
34209482a55SGreg Roach     * @param array<Tree>   $trees
34309482a55SGreg Roach     * @param array<string> $search
344a7a24840SGreg Roach     * @param int           $offset
345a7a24840SGreg Roach     * @param int           $limit
346a7a24840SGreg Roach     *
34736779af1SGreg Roach     * @return Collection<int,Source>
348a7a24840SGreg Roach     */
349a7a24840SGreg Roach    public function searchSourcesByName(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
35032cd2800SGreg Roach    {
35132cd2800SGreg Roach        $query = DB::table('sources')
352c0804649SGreg Roach            ->orderBy('s_name');
35332cd2800SGreg Roach
354a7a24840SGreg Roach        $this->whereTrees($query, 's_file', $trees);
355a7a24840SGreg Roach        $this->whereSearch($query, 's_name', $search);
356a7a24840SGreg Roach
357d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->sourceRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
35832cd2800SGreg Roach    }
35932cd2800SGreg Roach
36032cd2800SGreg Roach    /**
36163763244SGreg Roach     * Search for sources.
36263763244SGreg Roach     *
36309482a55SGreg Roach     * @param array<Tree>   $trees
36409482a55SGreg Roach     * @param array<string> $search
36563763244SGreg Roach     * @param int           $offset
36663763244SGreg Roach     * @param int           $limit
36763763244SGreg Roach     *
36836779af1SGreg Roach     * @return Collection<int,string>
36963763244SGreg Roach     */
37063763244SGreg Roach    public function searchSurnames(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
37163763244SGreg Roach    {
37263763244SGreg Roach        $query = DB::table('name');
37363763244SGreg Roach
37463763244SGreg Roach        $this->whereTrees($query, 'n_file', $trees);
37563763244SGreg Roach        $this->whereSearch($query, 'n_surname', $search);
37663763244SGreg Roach
37763763244SGreg Roach        return $query
37863763244SGreg Roach            ->groupBy(['n_surname'])
37963763244SGreg Roach            ->orderBy('n_surname')
38063763244SGreg Roach            ->skip($offset)
38163763244SGreg Roach            ->take($limit)
38263763244SGreg Roach            ->pluck('n_surname');
38363763244SGreg Roach    }
38463763244SGreg Roach
38563763244SGreg Roach    /**
386d4ac8227SGreg Roach     * Search for submissions.
387d4ac8227SGreg Roach     *
38809482a55SGreg Roach     * @param array<Tree>   $trees
38909482a55SGreg Roach     * @param array<string> $search
390d4ac8227SGreg Roach     * @param int           $offset
391d4ac8227SGreg Roach     * @param int           $limit
392d4ac8227SGreg Roach     *
39336779af1SGreg Roach     * @return Collection<int,Submission>
394d4ac8227SGreg Roach     */
395d4ac8227SGreg Roach    public function searchSubmissions(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
396d4ac8227SGreg Roach    {
397d4ac8227SGreg Roach        $query = DB::table('other')
398058ba724SGreg Roach            ->where('o_type', '=', Submission::RECORD_TYPE);
399d4ac8227SGreg Roach
400d4ac8227SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
401d4ac8227SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
402d4ac8227SGreg Roach
403d4ac8227SGreg Roach        return $this->paginateQuery($query, $this->submissionRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
404d4ac8227SGreg Roach    }
405d4ac8227SGreg Roach
406d4ac8227SGreg Roach    /**
40732cd2800SGreg Roach     * Search for submitters.
40832cd2800SGreg Roach     *
40909482a55SGreg Roach     * @param array<Tree>   $trees
41009482a55SGreg Roach     * @param array<string> $search
41132cd2800SGreg Roach     * @param int           $offset
41232cd2800SGreg Roach     * @param int           $limit
41332cd2800SGreg Roach     *
41436779af1SGreg Roach     * @return Collection<int,Submitter>
41532cd2800SGreg Roach     */
416a7a24840SGreg Roach    public function searchSubmitters(array $trees, array $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
41732cd2800SGreg Roach    {
41832cd2800SGreg Roach        $query = DB::table('other')
419058ba724SGreg Roach            ->where('o_type', '=', Submitter::RECORD_TYPE);
42032cd2800SGreg Roach
421a7a24840SGreg Roach        $this->whereTrees($query, 'o_file', $trees);
422a7a24840SGreg Roach        $this->whereSearch($query, 'o_gedcom', $search);
423a7a24840SGreg Roach
424d5ad3db0SGreg Roach        return $this->paginateQuery($query, $this->submitterRowMapper(), GedcomRecord::accessFilter(), $offset, $limit);
42532cd2800SGreg Roach    }
42632cd2800SGreg Roach
42732cd2800SGreg Roach    /**
428b68caec6SGreg Roach     * Search for places.
429b68caec6SGreg Roach     *
430b68caec6SGreg Roach     * @param Tree   $tree
431b68caec6SGreg Roach     * @param string $search
432b68caec6SGreg Roach     * @param int    $offset
433b68caec6SGreg Roach     * @param int    $limit
434b68caec6SGreg Roach     *
43536779af1SGreg Roach     * @return Collection<int,Place>
436b68caec6SGreg Roach     */
437b68caec6SGreg Roach    public function searchPlaces(Tree $tree, string $search, int $offset = 0, int $limit = PHP_INT_MAX): Collection
438b68caec6SGreg Roach    {
439b68caec6SGreg Roach        $query = DB::table('places AS p0')
440b68caec6SGreg Roach            ->where('p0.p_file', '=', $tree->id())
441b68caec6SGreg Roach            ->leftJoin('places AS p1', 'p1.p_id', '=', 'p0.p_parent_id')
442b68caec6SGreg Roach            ->leftJoin('places AS p2', 'p2.p_id', '=', 'p1.p_parent_id')
443b68caec6SGreg Roach            ->leftJoin('places AS p3', 'p3.p_id', '=', 'p2.p_parent_id')
444b68caec6SGreg Roach            ->leftJoin('places AS p4', 'p4.p_id', '=', 'p3.p_parent_id')
445b68caec6SGreg Roach            ->leftJoin('places AS p5', 'p5.p_id', '=', 'p4.p_parent_id')
446b68caec6SGreg Roach            ->leftJoin('places AS p6', 'p6.p_id', '=', 'p5.p_parent_id')
447b68caec6SGreg Roach            ->leftJoin('places AS p7', 'p7.p_id', '=', 'p6.p_parent_id')
448b68caec6SGreg Roach            ->leftJoin('places AS p8', 'p8.p_id', '=', 'p7.p_parent_id')
449b68caec6SGreg Roach            ->orderBy('p0.p_place')
450b68caec6SGreg Roach            ->orderBy('p1.p_place')
451b68caec6SGreg Roach            ->orderBy('p2.p_place')
452b68caec6SGreg Roach            ->orderBy('p3.p_place')
453b68caec6SGreg Roach            ->orderBy('p4.p_place')
454b68caec6SGreg Roach            ->orderBy('p5.p_place')
455b68caec6SGreg Roach            ->orderBy('p6.p_place')
456b68caec6SGreg Roach            ->orderBy('p7.p_place')
457b68caec6SGreg Roach            ->orderBy('p8.p_place')
458b68caec6SGreg Roach            ->select([
459b68caec6SGreg Roach                'p0.p_place AS place0',
460b68caec6SGreg Roach                'p1.p_place AS place1',
461b68caec6SGreg Roach                'p2.p_place AS place2',
462b68caec6SGreg Roach                'p3.p_place AS place3',
463b68caec6SGreg Roach                'p4.p_place AS place4',
464b68caec6SGreg Roach                'p5.p_place AS place5',
465b68caec6SGreg Roach                'p6.p_place AS place6',
466b68caec6SGreg Roach                'p7.p_place AS place7',
467b68caec6SGreg Roach                'p8.p_place AS place8',
468b68caec6SGreg Roach            ]);
469b68caec6SGreg Roach
470b68caec6SGreg Roach        // Filter each level of the hierarchy.
471b68caec6SGreg Roach        foreach (explode(',', $search, 9) as $level => $string) {
472b5961194SGreg Roach            $query->where('p' . $level . '.p_place', 'LIKE', '%' . addcslashes($string, '\\%_') . '%');
473b68caec6SGreg Roach        }
474b68caec6SGreg Roach
475f70bcff5SGreg Roach        $row_mapper = static function (object $row) use ($tree): Place {
476b68caec6SGreg Roach            $place = implode(', ', array_filter((array) $row));
477b68caec6SGreg Roach
478b68caec6SGreg Roach            return new Place($place, $tree);
479b68caec6SGreg Roach        };
480b68caec6SGreg Roach
4816c2179e2SGreg Roach        $filter = static function (): bool {
482a7a24840SGreg Roach            return true;
483a7a24840SGreg Roach        };
484b68caec6SGreg Roach
485a7a24840SGreg Roach        return $this->paginateQuery($query, $row_mapper, $filter, $offset, $limit);
486a7a24840SGreg Roach    }
487b68caec6SGreg Roach
488b68caec6SGreg Roach    /**
48909482a55SGreg Roach     * @param array<Tree>          $trees
490d8809d62SGreg Roach     * @param array<string,string> $fields
491d8809d62SGreg Roach     * @param array<string,string> $modifiers
492dfb2cda2SGreg Roach     *
49336779af1SGreg Roach     * @return Collection<int,Individual>
494dfb2cda2SGreg Roach     */
495dfb2cda2SGreg Roach    public function searchIndividualsAdvanced(array $trees, array $fields, array $modifiers): Collection
496dfb2cda2SGreg Roach    {
497dfb2cda2SGreg Roach        $fields = array_filter($fields);
498dfb2cda2SGreg Roach
499dfb2cda2SGreg Roach        $query = DB::table('individuals')
500dfb2cda2SGreg Roach            ->select(['individuals.*'])
501dfb2cda2SGreg Roach            ->distinct();
502dfb2cda2SGreg Roach
503dfb2cda2SGreg Roach        $this->whereTrees($query, 'i_file', $trees);
504dfb2cda2SGreg Roach
505dfb2cda2SGreg Roach        // Join the following tables
506dfb2cda2SGreg Roach        $father_name   = false;
507dfb2cda2SGreg Roach        $mother_name   = false;
508dfb2cda2SGreg Roach        $spouse_family = false;
509dfb2cda2SGreg Roach        $indi_name     = false;
51056946b7aSGreg Roach        $indi_dates    = [];
51156946b7aSGreg Roach        $fam_dates     = [];
512dfb2cda2SGreg Roach        $indi_plac     = false;
513dfb2cda2SGreg Roach        $fam_plac      = false;
514dfb2cda2SGreg Roach
515dfb2cda2SGreg Roach        foreach ($fields as $field_name => $field_value) {
516dfb2cda2SGreg Roach            if ($field_value !== '') {
5172f86083cSGreg Roach                if (str_starts_with($field_name, 'FATHER:NAME')) {
518dfb2cda2SGreg Roach                    $father_name = true;
5192f86083cSGreg Roach                } elseif (str_starts_with($field_name, 'MOTHER:NAME')) {
520dfb2cda2SGreg Roach                    $mother_name = true;
5212f86083cSGreg Roach                } elseif (str_starts_with($field_name, 'INDI:NAME:GIVN')) {
52256946b7aSGreg Roach                    $indi_name = true;
5232f86083cSGreg Roach                } elseif (str_starts_with($field_name, 'INDI:NAME:SURN')) {
5242f86083cSGreg Roach                    $indi_name = true;
5252f86083cSGreg Roach                } elseif (str_starts_with($field_name, 'FAM:')) {
526dfb2cda2SGreg Roach                    $spouse_family = true;
5272f86083cSGreg Roach                    if (str_ends_with($field_name, ':DATE')) {
5282f86083cSGreg Roach                        $fam_dates[] = explode(':', $field_name)[1];
5292f86083cSGreg Roach                    } elseif (str_ends_with($field_name, ':PLAC')) {
53056946b7aSGreg Roach                        $fam_plac = true;
53156946b7aSGreg Roach                    }
5322f86083cSGreg Roach                } elseif (str_starts_with($field_name, 'INDI:')) {
5332f86083cSGreg Roach                    if (str_ends_with($field_name, ':DATE')) {
5342f86083cSGreg Roach                        $indi_dates[] = explode(':', $field_name)[1];
5352f86083cSGreg Roach                    } elseif (str_ends_with($field_name, ':PLAC')) {
536dfb2cda2SGreg Roach                        $indi_plac = true;
537dfb2cda2SGreg Roach                    }
538dfb2cda2SGreg Roach                }
539dfb2cda2SGreg Roach            }
540dfb2cda2SGreg Roach        }
541dfb2cda2SGreg Roach
542dfb2cda2SGreg Roach        if ($father_name || $mother_name) {
5430b5fd0a6SGreg Roach            $query->join('link AS l1', static function (JoinClause $join): void {
544dfb2cda2SGreg Roach                $join
545dfb2cda2SGreg Roach                    ->on('l1.l_file', '=', 'individuals.i_file')
546dfb2cda2SGreg Roach                    ->on('l1.l_from', '=', 'individuals.i_id')
547dfb2cda2SGreg Roach                    ->where('l1.l_type', '=', 'FAMC');
548dfb2cda2SGreg Roach            });
549dfb2cda2SGreg Roach
550dfb2cda2SGreg Roach            if ($father_name) {
5510b5fd0a6SGreg Roach                $query->join('link AS l2', static function (JoinClause $join): void {
552dfb2cda2SGreg Roach                    $join
553dfb2cda2SGreg Roach                        ->on('l2.l_file', '=', 'l1.l_file')
554dfb2cda2SGreg Roach                        ->on('l2.l_from', '=', 'l1.l_to')
555dfb2cda2SGreg Roach                        ->where('l2.l_type', '=', 'HUSB');
556dfb2cda2SGreg Roach                });
5570b5fd0a6SGreg Roach                $query->join('name AS father_name', static function (JoinClause $join): void {
558dfb2cda2SGreg Roach                    $join
559dfb2cda2SGreg Roach                        ->on('father_name.n_file', '=', 'l2.l_file')
560dfb2cda2SGreg Roach                        ->on('father_name.n_id', '=', 'l2.l_to');
561dfb2cda2SGreg Roach                });
562dfb2cda2SGreg Roach            }
563dfb2cda2SGreg Roach
564dfb2cda2SGreg Roach            if ($mother_name) {
5650b5fd0a6SGreg Roach                $query->join('link AS l3', static function (JoinClause $join): void {
566dfb2cda2SGreg Roach                    $join
567dfb2cda2SGreg Roach                        ->on('l3.l_file', '=', 'l1.l_file')
568dfb2cda2SGreg Roach                        ->on('l3.l_from', '=', 'l1.l_to')
569dfb2cda2SGreg Roach                        ->where('l3.l_type', '=', 'WIFE');
570dfb2cda2SGreg Roach                });
5710b5fd0a6SGreg Roach                $query->join('name AS mother_name', static function (JoinClause $join): void {
572dfb2cda2SGreg Roach                    $join
573dfb2cda2SGreg Roach                        ->on('mother_name.n_file', '=', 'l3.l_file')
574dfb2cda2SGreg Roach                        ->on('mother_name.n_id', '=', 'l3.l_to');
575dfb2cda2SGreg Roach                });
576dfb2cda2SGreg Roach            }
577dfb2cda2SGreg Roach        }
578dfb2cda2SGreg Roach
579dfb2cda2SGreg Roach        if ($spouse_family) {
5800b5fd0a6SGreg Roach            $query->join('link AS l4', static function (JoinClause $join): void {
581dfb2cda2SGreg Roach                $join
582dfb2cda2SGreg Roach                    ->on('l4.l_file', '=', 'individuals.i_file')
583dfb2cda2SGreg Roach                    ->on('l4.l_from', '=', 'individuals.i_id')
584dfb2cda2SGreg Roach                    ->where('l4.l_type', '=', 'FAMS');
585dfb2cda2SGreg Roach            });
5860b5fd0a6SGreg Roach            $query->join('families AS spouse_families', static function (JoinClause $join): void {
587dfb2cda2SGreg Roach                $join
588dfb2cda2SGreg Roach                    ->on('spouse_families.f_file', '=', 'l4.l_file')
589dfb2cda2SGreg Roach                    ->on('spouse_families.f_id', '=', 'l4.l_to');
590dfb2cda2SGreg Roach            });
591dfb2cda2SGreg Roach        }
592dfb2cda2SGreg Roach
593dfb2cda2SGreg Roach        if ($indi_name) {
5940b5fd0a6SGreg Roach            $query->join('name AS individual_name', static function (JoinClause $join): void {
595dfb2cda2SGreg Roach                $join
596dfb2cda2SGreg Roach                    ->on('individual_name.n_file', '=', 'individuals.i_file')
597dfb2cda2SGreg Roach                    ->on('individual_name.n_id', '=', 'individuals.i_id');
598dfb2cda2SGreg Roach            });
599dfb2cda2SGreg Roach        }
600dfb2cda2SGreg Roach
60156946b7aSGreg Roach        foreach (array_unique($indi_dates) as $indi_date) {
60256946b7aSGreg Roach            $query->join('dates AS date_' . $indi_date, static function (JoinClause $join) use ($indi_date): void {
603dfb2cda2SGreg Roach                $join
60456946b7aSGreg Roach                    ->on('date_' . $indi_date . '.d_file', '=', 'individuals.i_file')
60556946b7aSGreg Roach                    ->on('date_' . $indi_date . '.d_gid', '=', 'individuals.i_id');
606dfb2cda2SGreg Roach            });
607dfb2cda2SGreg Roach        }
608dfb2cda2SGreg Roach
60956946b7aSGreg Roach        foreach (array_unique($fam_dates) as $fam_date) {
61056946b7aSGreg Roach            $query->join('dates AS date_' . $fam_date, static function (JoinClause $join) use ($fam_date): void {
611dfb2cda2SGreg Roach                $join
612b06d667bSGreg Roach                    ->on('date_' . $fam_date . '.d_file', '=', 'spouse_families.f_file')
613b06d667bSGreg Roach                    ->on('date_' . $fam_date . '.d_gid', '=', 'spouse_families.f_id');
614dfb2cda2SGreg Roach            });
615dfb2cda2SGreg Roach        }
616dfb2cda2SGreg Roach
617dfb2cda2SGreg Roach        if ($indi_plac) {
6180b5fd0a6SGreg Roach            $query->join('placelinks AS individual_placelinks', static function (JoinClause $join): void {
619dfb2cda2SGreg Roach                $join
620dfb2cda2SGreg Roach                    ->on('individual_placelinks.pl_file', '=', 'individuals.i_file')
621dfb2cda2SGreg Roach                    ->on('individual_placelinks.pl_gid', '=', 'individuals.i_id');
622dfb2cda2SGreg Roach            });
6230b5fd0a6SGreg Roach            $query->join('places AS individual_places', static function (JoinClause $join): void {
624dfb2cda2SGreg Roach                $join
625dfb2cda2SGreg Roach                    ->on('individual_places.p_file', '=', 'individual_placelinks.pl_file')
626dfb2cda2SGreg Roach                    ->on('individual_places.p_id', '=', 'individual_placelinks.pl_p_id');
627dfb2cda2SGreg Roach            });
628dfb2cda2SGreg Roach        }
629dfb2cda2SGreg Roach
630dfb2cda2SGreg Roach        if ($fam_plac) {
6310b5fd0a6SGreg Roach            $query->join('placelinks AS familyl_placelinks', static function (JoinClause $join): void {
632dfb2cda2SGreg Roach                $join
633dfb2cda2SGreg Roach                    ->on('familyl_placelinks.pl_file', '=', 'individuals.i_file')
634dfb2cda2SGreg Roach                    ->on('familyl_placelinks.pl_gid', '=', 'individuals.i_id');
635dfb2cda2SGreg Roach            });
6360b5fd0a6SGreg Roach            $query->join('places AS family_places', static function (JoinClause $join): void {
637dfb2cda2SGreg Roach                $join
638dfb2cda2SGreg Roach                    ->on('family_places.p_file', '=', 'familyl_placelinks.pl_file')
639dfb2cda2SGreg Roach                    ->on('family_places.p_id', '=', 'familyl_placelinks.pl_p_id');
640dfb2cda2SGreg Roach            });
641dfb2cda2SGreg Roach        }
642dfb2cda2SGreg Roach
643dfb2cda2SGreg Roach        foreach ($fields as $field_name => $field_value) {
64456946b7aSGreg Roach            $parts = explode(':', $field_name . ':::');
6452f86083cSGreg Roach            if (str_starts_with($field_name, 'INDI:NAME:')) {
6462f86083cSGreg Roach                switch ($field_name) {
6472f86083cSGreg Roach                    case 'INDI:NAME:GIVN':
648dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
649dfb2cda2SGreg Roach                            case 'EXACT':
650dfb2cda2SGreg Roach                                $query->where('individual_name.n_givn', '=', $field_value);
651dfb2cda2SGreg Roach                                break;
652dfb2cda2SGreg Roach                            case 'BEGINS':
653dfb2cda2SGreg Roach                                $query->where('individual_name.n_givn', 'LIKE', $field_value . '%');
654dfb2cda2SGreg Roach                                break;
655dfb2cda2SGreg Roach                            case 'CONTAINS':
656dfb2cda2SGreg Roach                                $query->where('individual_name.n_givn', 'LIKE', '%' . $field_value . '%');
657dfb2cda2SGreg Roach                                break;
658dfb2cda2SGreg Roach                            case 'SDX_STD':
659dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
660dfb2cda2SGreg Roach                                if ($sdx !== '') {
661dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_givn_std', $sdx);
662dfb2cda2SGreg Roach                                } else {
663dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
664dfb2cda2SGreg Roach                                    $query->where('individual_name.n_givn', 'LIKE', '%' . $field_value . '%');
665dfb2cda2SGreg Roach                                }
666dfb2cda2SGreg Roach                                break;
667dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
668dfb2cda2SGreg Roach                            case 'SDX_DM':
669dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
670dfb2cda2SGreg Roach                                if ($sdx !== '') {
671dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_givn_dm', $sdx);
672dfb2cda2SGreg Roach                                } else {
673dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
674dfb2cda2SGreg Roach                                    $query->where('individual_name.n_givn', 'LIKE', '%' . $field_value . '%');
675dfb2cda2SGreg Roach                                }
676dfb2cda2SGreg Roach                                break;
677dfb2cda2SGreg Roach                        }
678788f881dSGreg Roach                        unset($fields[$field_name]);
679dfb2cda2SGreg Roach                        break;
6802f86083cSGreg Roach                    case 'INDI:NAME:SURN':
681dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
682dfb2cda2SGreg Roach                            case 'EXACT':
683fc6d23eeSGreg Roach                                $query->where(function (Builder $query) use ($field_value): void {
684fc6d23eeSGreg Roach                                    $query
685fc6d23eeSGreg Roach                                        ->where('individual_name.n_surn', '=', $field_value)
686fc6d23eeSGreg Roach                                        ->orWhere('individual_name.n_surname', '=', $field_value);
687fc6d23eeSGreg Roach                                });
688dfb2cda2SGreg Roach                                break;
689dfb2cda2SGreg Roach                            case 'BEGINS':
690fc6d23eeSGreg Roach                                $query->where(function (Builder $query) use ($field_value): void {
691fc6d23eeSGreg Roach                                    $query
692fc6d23eeSGreg Roach                                        ->where('individual_name.n_surn', 'LIKE', $field_value . '%')
6939875d474SGreg Roach                                        ->orWhere('individual_name.n_surname', 'LIKE', $field_value . '%');
694fc6d23eeSGreg Roach                                });
695dfb2cda2SGreg Roach                                break;
696dfb2cda2SGreg Roach                            case 'CONTAINS':
697fc6d23eeSGreg Roach                                $query->where(function (Builder $query) use ($field_value): void {
698fc6d23eeSGreg Roach                                    $query
699fc6d23eeSGreg Roach                                        ->where('individual_name.n_surn', 'LIKE', '%' . $field_value . '%')
7009875d474SGreg Roach                                        ->orWhere('individual_name.n_surname', 'LIKE', '%' . $field_value . '%');
701fc6d23eeSGreg Roach                                });
702dfb2cda2SGreg Roach                                break;
703dfb2cda2SGreg Roach                            case 'SDX_STD':
704dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
705dfb2cda2SGreg Roach                                if ($sdx !== '') {
706dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_surn_std', $sdx);
707dfb2cda2SGreg Roach                                } else {
708dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
709fc6d23eeSGreg Roach                                    $query->where(function (Builder $query) use ($field_value): void {
710fc6d23eeSGreg Roach                                        $query
711fc6d23eeSGreg Roach                                            ->where('individual_name.n_surn', 'LIKE', '%' . $field_value . '%')
7129875d474SGreg Roach                                            ->orWhere('individual_name.n_surname', 'LIKE', '%' . $field_value . '%');
713fc6d23eeSGreg Roach                                    });
714dfb2cda2SGreg Roach                                }
715dfb2cda2SGreg Roach                                break;
716dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
717dfb2cda2SGreg Roach                            case 'SDX_DM':
718dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
719dfb2cda2SGreg Roach                                if ($sdx !== '') {
720dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, 'individual_name.n_soundex_surn_dm', $sdx);
721dfb2cda2SGreg Roach                                } else {
722dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
7239875d474SGreg Roach                                    $query->where(function (Builder $query) use ($field_value): void {
7249875d474SGreg Roach                                        $query
7259875d474SGreg Roach                                            ->where('individual_name.n_surn', 'LIKE', '%' . $field_value . '%')
7269875d474SGreg Roach                                            ->orWhere('individual_name.n_surname', 'LIKE', '%' . $field_value . '%');
7279875d474SGreg Roach                                    });
728dfb2cda2SGreg Roach                                }
729dfb2cda2SGreg Roach                                break;
730dfb2cda2SGreg Roach                        }
731b4adec9eSGreg Roach                        unset($fields[$field_name]);
732dfb2cda2SGreg Roach                        break;
7332f86083cSGreg Roach                    case 'INDI:NAME:NICK':
7342f86083cSGreg Roach                    case 'INDI:NAME:_MARNM':
7352f86083cSGreg Roach                    case 'INDI:NAME:_HEB':
7362f86083cSGreg Roach                    case 'INDI:NAME:_AKA':
7372f86083cSGreg Roach                        $like = "%\n1 NAME%\n2 " . $parts[2] . ' %' . preg_quote($field_value, '/') . '%';
738b4adec9eSGreg Roach                        $query->where('individuals.i_gedcom', 'LIKE', $like);
739dfb2cda2SGreg Roach                        break;
740dfb2cda2SGreg Roach                }
7412f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'INDI:') && str_ends_with($field_name, ':DATE')) {
742dfb2cda2SGreg Roach                $date = new Date($field_value);
743dfb2cda2SGreg Roach                if ($date->isOK()) {
744d8809d62SGreg Roach                    $delta = 365 * (int) ($modifiers[$field_name] ?? 0);
745dfb2cda2SGreg Roach                    $query
7462f86083cSGreg Roach                        ->where('date_' . $parts[1] . '.d_fact', '=', $parts[1])
7472f86083cSGreg Roach                        ->where('date_' . $parts[1] . '.d_julianday1', '>=', $date->minimumJulianDay() - $delta)
7482f86083cSGreg Roach                        ->where('date_' . $parts[1] . '.d_julianday2', '<=', $date->maximumJulianDay() + $delta);
749dfb2cda2SGreg Roach                }
750dfb2cda2SGreg Roach                unset($fields[$field_name]);
7512f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'FAM:') && str_ends_with($field_name, ':DATE')) {
752dfb2cda2SGreg Roach                $date = new Date($field_value);
753dfb2cda2SGreg Roach                if ($date->isOK()) {
754d8809d62SGreg Roach                    $delta = 365 * (int) ($modifiers[$field_name] ?? 0);
755dfb2cda2SGreg Roach                    $query
75656946b7aSGreg Roach                        ->where('date_' . $parts[1] . '.d_fact', '=', $parts[1])
75756946b7aSGreg Roach                        ->where('date_' . $parts[1] . '.d_julianday1', '>=', $date->minimumJulianDay() - $delta)
75856946b7aSGreg Roach                        ->where('date_' . $parts[1] . '.d_julianday2', '<=', $date->maximumJulianDay() + $delta);
759dfb2cda2SGreg Roach                }
760dfb2cda2SGreg Roach                unset($fields[$field_name]);
7612f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'INDI:') && str_ends_with($field_name, ':PLAC')) {
762dfb2cda2SGreg Roach                // SQL can only link a place to a person/family, not to an event.
763dfb2cda2SGreg Roach                $query->where('individual_places.p_place', 'LIKE', '%' . $field_value . '%');
7642f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'FAM:') && str_ends_with($field_name, ':PLAC')) {
765dfb2cda2SGreg Roach                // SQL can only link a place to a person/family, not to an event.
766dfb2cda2SGreg Roach                $query->where('family_places.p_place', 'LIKE', '%' . $field_value . '%');
7672f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'MOTHER:NAME:') || str_starts_with($field_name, 'FATHER:NAME:')) {
7682f86083cSGreg Roach                $table = str_starts_with($field_name, 'FATHER:NAME:') ? 'father_name' : 'mother_name';
7692f86083cSGreg Roach                switch ($parts[2]) {
770dfb2cda2SGreg Roach                    case 'GIVN':
771dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
772dfb2cda2SGreg Roach                            case 'EXACT':
773dfb2cda2SGreg Roach                                $query->where($table . '.n_givn', '=', $field_value);
774dfb2cda2SGreg Roach                                break;
775dfb2cda2SGreg Roach                            case 'BEGINS':
776dfb2cda2SGreg Roach                                $query->where($table . '.n_givn', 'LIKE', $field_value . '%');
777dfb2cda2SGreg Roach                                break;
778dfb2cda2SGreg Roach                            case 'CONTAINS':
779dfb2cda2SGreg Roach                                $query->where($table . '.n_givn', 'LIKE', '%' . $field_value . '%');
780dfb2cda2SGreg Roach                                break;
781dfb2cda2SGreg Roach                            case 'SDX_STD':
782dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
783dfb2cda2SGreg Roach                                if ($sdx !== '') {
784dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_givn_std', $sdx);
785dfb2cda2SGreg Roach                                } else {
786dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
787dfb2cda2SGreg Roach                                    $query->where($table . '.n_givn', 'LIKE', '%' . $field_value . '%');
788dfb2cda2SGreg Roach                                }
789dfb2cda2SGreg Roach                                break;
790dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
791dfb2cda2SGreg Roach                            case 'SDX_DM':
792dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
793dfb2cda2SGreg Roach                                if ($sdx !== '') {
794dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_givn_dm', $sdx);
795dfb2cda2SGreg Roach                                } else {
796dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
797dfb2cda2SGreg Roach                                    $query->where($table . '.n_givn', 'LIKE', '%' . $field_value . '%');
798dfb2cda2SGreg Roach                                }
799dfb2cda2SGreg Roach                                break;
800dfb2cda2SGreg Roach                        }
801dfb2cda2SGreg Roach                        break;
802dfb2cda2SGreg Roach                    case 'SURN':
803dfb2cda2SGreg Roach                        switch ($modifiers[$field_name]) {
804dfb2cda2SGreg Roach                            case 'EXACT':
805dfb2cda2SGreg Roach                                $query->where($table . '.n_surn', '=', $field_value);
806dfb2cda2SGreg Roach                                break;
807dfb2cda2SGreg Roach                            case 'BEGINS':
808dfb2cda2SGreg Roach                                $query->where($table . '.n_surn', 'LIKE', $field_value . '%');
809dfb2cda2SGreg Roach                                break;
810dfb2cda2SGreg Roach                            case 'CONTAINS':
811dfb2cda2SGreg Roach                                $query->where($table . '.n_surn', 'LIKE', '%' . $field_value . '%');
812dfb2cda2SGreg Roach                                break;
813dfb2cda2SGreg Roach                            case 'SDX_STD':
814dfb2cda2SGreg Roach                                $sdx = Soundex::russell($field_value);
815dfb2cda2SGreg Roach                                if ($sdx !== '') {
816dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_surn_std', $sdx);
817dfb2cda2SGreg Roach                                } else {
818dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
819dfb2cda2SGreg Roach                                    $query->where($table . '.n_surn', 'LIKE', '%' . $field_value . '%');
820dfb2cda2SGreg Roach                                }
821dfb2cda2SGreg Roach                                break;
822dfb2cda2SGreg Roach                            case 'SDX': // SDX uses DM by default.
823dfb2cda2SGreg Roach                            case 'SDX_DM':
824dfb2cda2SGreg Roach                                $sdx = Soundex::daitchMokotoff($field_value);
825dfb2cda2SGreg Roach                                if ($sdx !== '') {
826dfb2cda2SGreg Roach                                    $this->wherePhonetic($query, $table . '.n_soundex_surn_dm', $sdx);
827dfb2cda2SGreg Roach                                } else {
828dfb2cda2SGreg Roach                                    // No phonetic content? Use a substring match
829dfb2cda2SGreg Roach                                    $query->where($table . '.n_surn', 'LIKE', '%' . $field_value . '%');
830dfb2cda2SGreg Roach                                }
831dfb2cda2SGreg Roach                                break;
832dfb2cda2SGreg Roach                        }
833dfb2cda2SGreg Roach                        break;
834dfb2cda2SGreg Roach                }
835dfb2cda2SGreg Roach                unset($fields[$field_name]);
8362f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'FAM:')) {
837dfb2cda2SGreg Roach                // e.g. searches for occupation, religion, note, etc.
838dfb2cda2SGreg Roach                // Initial matching only.  Need PHP to apply filter.
8393c480c6bSGreg Roach                $query->where('spouse_families.f_gedcom', 'LIKE', "%\n1 " . $parts[1] . ' %' . $field_value . '%');
8402f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'INDI:') && str_ends_with($field_name, ':TYPE')) {
841dfb2cda2SGreg Roach                // Initial matching only.  Need PHP to apply filter.
8422f86083cSGreg Roach                $query->where('individuals.i_gedcom', 'LIKE', "%\n1 " . $parts[1] . "%\n2 TYPE %" . $field_value . '%');
8432f86083cSGreg Roach            } elseif (str_starts_with($field_name, 'INDI:')) {
844dfb2cda2SGreg Roach                // e.g. searches for occupation, religion, note, etc.
845dfb2cda2SGreg Roach                // Initial matching only.  Need PHP to apply filter.
8462f86083cSGreg Roach                $query->where('individuals.i_gedcom', 'LIKE', "%\n1 " . $parts[1] . '%' . $parts[2] . '%' . $field_value . '%');
847dfb2cda2SGreg Roach            }
848dfb2cda2SGreg Roach        }
849b4adec9eSGreg Roach
850dfb2cda2SGreg Roach        return $query
851dfb2cda2SGreg Roach            ->get()
85252a8ef61SGreg Roach            ->each($this->rowLimiter())
853d5ad3db0SGreg Roach            ->map($this->individualRowMapper())
854dfb2cda2SGreg Roach            ->filter(GedcomRecord::accessFilter())
8550b5fd0a6SGreg Roach            ->filter(static function (Individual $individual) use ($fields): bool {
856c5457947SGreg Roach                // Check for searches which were only partially matched by SQL
857dfb2cda2SGreg Roach                foreach ($fields as $field_name => $field_value) {
858c5457947SGreg Roach                    $parts = explode(':', $field_name . '::::');
859dfb2cda2SGreg Roach
8602f86083cSGreg Roach                    if (str_starts_with($field_name, 'INDI:NAME:') && $field_name !== 'INDI:NAME:GIVN' && $field_name !== 'INDI:NAME:SURN') {
8612f86083cSGreg Roach                        $regex = '/\n1 NAME.*(?:\n2.*)*\n2 ' . $parts[2] . ' .*' . preg_quote($field_value, '/') . '/i';
862b4adec9eSGreg Roach
863b4adec9eSGreg Roach                        if (preg_match($regex, $individual->gedcom())) {
864b4adec9eSGreg Roach                            continue;
865b4adec9eSGreg Roach                        }
866b4adec9eSGreg Roach
867b4adec9eSGreg Roach                        return false;
868b4adec9eSGreg Roach                    }
869b4adec9eSGreg Roach
870b4adec9eSGreg Roach                    $regex = '/' . preg_quote($field_value, '/') . '/i';
871b4adec9eSGreg Roach
8722f86083cSGreg Roach                    if (str_starts_with($field_name, 'INDI:') && str_ends_with($field_name, ':PLAC')) {
8732f86083cSGreg Roach                        foreach ($individual->facts([$parts[1]]) as $fact) {
874392561bbSGreg Roach                            if (preg_match($regex, $fact->place()->gedcomName())) {
875c5457947SGreg Roach                                continue 2;
876dfb2cda2SGreg Roach                            }
877a41e65f0SGreg Roach                        }
878c5457947SGreg Roach                        return false;
879c5457947SGreg Roach                    }
880c5457947SGreg Roach
8812f86083cSGreg Roach                    if (str_starts_with($field_name, 'FAM:') && str_ends_with($field_name, ':PLAC')) {
88239ca88baSGreg Roach                        foreach ($individual->spouseFamilies() as $family) {
883a41e65f0SGreg Roach                            foreach ($family->facts([$parts[1]]) as $fact) {
884392561bbSGreg Roach                                if (preg_match($regex, $fact->place()->gedcomName())) {
8853b3576aeSGreg Roach                                    continue 3;
886a41e65f0SGreg Roach                                }
887dfb2cda2SGreg Roach                            }
888dfb2cda2SGreg Roach                        }
889c5457947SGreg Roach                        return false;
890c5457947SGreg Roach                    }
891c5457947SGreg Roach
8922f86083cSGreg Roach                    if ($field_name === 'INDI:FACT:TYPE' || $field_name === 'INDI:EVEN:TYPE' || $field_name === 'INDI:CHAN:_WT_USER') {
8932f86083cSGreg Roach                        foreach ($individual->facts([$parts[1]]) as $fact) {
8942f86083cSGreg Roach                            if (preg_match($regex, $fact->attribute($parts[2]))) {
8952f86083cSGreg Roach                                continue 2;
8962f86083cSGreg Roach                            }
8972f86083cSGreg Roach                        }
8982f86083cSGreg Roach
8992f86083cSGreg Roach                        return false;
9002f86083cSGreg Roach                    }
9012f86083cSGreg Roach
9022f86083cSGreg Roach                    if (str_starts_with($field_name, 'INDI:')) {
9032f86083cSGreg Roach                        foreach ($individual->facts([$parts[1]]) as $fact) {
9042f86083cSGreg Roach                            if (preg_match($regex, $fact->value())) {
9052f86083cSGreg Roach                                continue 2;
9062f86083cSGreg Roach                            }
9072f86083cSGreg Roach                        }
9082f86083cSGreg Roach
9092f86083cSGreg Roach                        return false;
9102f86083cSGreg Roach                    }
9112f86083cSGreg Roach
9122f86083cSGreg Roach                    if (str_starts_with($field_name, 'FAM:')) {
91339ca88baSGreg Roach                        foreach ($individual->spouseFamilies() as $family) {
914a41e65f0SGreg Roach                            foreach ($family->facts([$parts[1]]) as $fact) {
915a41e65f0SGreg Roach                                if (preg_match($regex, $fact->value())) {
916c5457947SGreg Roach                                    continue 3;
917a41e65f0SGreg Roach                                }
918dfb2cda2SGreg Roach                            }
919dfb2cda2SGreg Roach                        }
920c5457947SGreg Roach                        return false;
921c5457947SGreg Roach                    }
922c5457947SGreg Roach                }
923dfb2cda2SGreg Roach
924dfb2cda2SGreg Roach                return true;
925dfb2cda2SGreg Roach            });
926dfb2cda2SGreg Roach    }
927dfb2cda2SGreg Roach
928dfb2cda2SGreg Roach    /**
929dfb2cda2SGreg Roach     * @param string      $soundex
930dfb2cda2SGreg Roach     * @param string      $lastname
931dfb2cda2SGreg Roach     * @param string      $firstname
932dfb2cda2SGreg Roach     * @param string      $place
93309482a55SGreg Roach     * @param array<Tree> $search_trees
934dfb2cda2SGreg Roach     *
93536779af1SGreg Roach     * @return Collection<int,Individual>
936dfb2cda2SGreg Roach     */
937dfb2cda2SGreg Roach    public function searchIndividualsPhonetic(string $soundex, string $lastname, string $firstname, string $place, array $search_trees): Collection
938dfb2cda2SGreg Roach    {
939dfb2cda2SGreg Roach        switch ($soundex) {
940dfb2cda2SGreg Roach            default:
941dfb2cda2SGreg Roach            case 'Russell':
942dfb2cda2SGreg Roach                $givn_sdx   = Soundex::russell($firstname);
943dfb2cda2SGreg Roach                $surn_sdx   = Soundex::russell($lastname);
944dfb2cda2SGreg Roach                $plac_sdx   = Soundex::russell($place);
945dfb2cda2SGreg Roach                $givn_field = 'n_soundex_givn_std';
946dfb2cda2SGreg Roach                $surn_field = 'n_soundex_surn_std';
947dfb2cda2SGreg Roach                $plac_field = 'p_std_soundex';
948dfb2cda2SGreg Roach                break;
949dfb2cda2SGreg Roach            case 'DaitchM':
950dfb2cda2SGreg Roach                $givn_sdx   = Soundex::daitchMokotoff($firstname);
951dfb2cda2SGreg Roach                $surn_sdx   = Soundex::daitchMokotoff($lastname);
952dfb2cda2SGreg Roach                $plac_sdx   = Soundex::daitchMokotoff($place);
953dfb2cda2SGreg Roach                $givn_field = 'n_soundex_givn_dm';
954dfb2cda2SGreg Roach                $surn_field = 'n_soundex_surn_dm';
955dfb2cda2SGreg Roach                $plac_field = 'p_dm_soundex';
956dfb2cda2SGreg Roach                break;
957dfb2cda2SGreg Roach        }
958dfb2cda2SGreg Roach
959dfb2cda2SGreg Roach        // Nothing to search for? Return nothing.
960dfb2cda2SGreg Roach        if ($givn_sdx === '' && $surn_sdx === '' && $plac_sdx === '') {
9613fda39a7SGreg Roach            return new Collection();
962dfb2cda2SGreg Roach        }
963dfb2cda2SGreg Roach
964dfb2cda2SGreg Roach        $query = DB::table('individuals')
965dfb2cda2SGreg Roach            ->select(['individuals.*'])
966dfb2cda2SGreg Roach            ->distinct();
967dfb2cda2SGreg Roach
968dfb2cda2SGreg Roach        $this->whereTrees($query, 'i_file', $search_trees);
969dfb2cda2SGreg Roach
970dfb2cda2SGreg Roach        if ($plac_sdx !== '') {
9710b5fd0a6SGreg Roach            $query->join('placelinks', static function (JoinClause $join): void {
972dfb2cda2SGreg Roach                $join
973dfb2cda2SGreg Roach                    ->on('placelinks.pl_file', '=', 'individuals.i_file')
974dfb2cda2SGreg Roach                    ->on('placelinks.pl_gid', '=', 'individuals.i_id');
975dfb2cda2SGreg Roach            });
9760b5fd0a6SGreg Roach            $query->join('places', static function (JoinClause $join): void {
977dfb2cda2SGreg Roach                $join
978dfb2cda2SGreg Roach                    ->on('places.p_file', '=', 'placelinks.pl_file')
979dfb2cda2SGreg Roach                    ->on('places.p_id', '=', 'placelinks.pl_p_id');
980dfb2cda2SGreg Roach            });
981dfb2cda2SGreg Roach
982dfb2cda2SGreg Roach            $this->wherePhonetic($query, $plac_field, $plac_sdx);
983dfb2cda2SGreg Roach        }
984dfb2cda2SGreg Roach
985dfb2cda2SGreg Roach        if ($givn_sdx !== '' || $surn_sdx !== '') {
9860b5fd0a6SGreg Roach            $query->join('name', static function (JoinClause $join): void {
987dfb2cda2SGreg Roach                $join
988dfb2cda2SGreg Roach                    ->on('name.n_file', '=', 'individuals.i_file')
989dfb2cda2SGreg Roach                    ->on('name.n_id', '=', 'individuals.i_id');
990dfb2cda2SGreg Roach            });
991dfb2cda2SGreg Roach
992dfb2cda2SGreg Roach            $this->wherePhonetic($query, $givn_field, $givn_sdx);
993dfb2cda2SGreg Roach            $this->wherePhonetic($query, $surn_field, $surn_sdx);
994dfb2cda2SGreg Roach        }
995dfb2cda2SGreg Roach
996dfb2cda2SGreg Roach        return $query
997dfb2cda2SGreg Roach            ->get()
99852a8ef61SGreg Roach            ->each($this->rowLimiter())
999d5ad3db0SGreg Roach            ->map($this->individualRowMapper())
1000dfb2cda2SGreg Roach            ->filter(GedcomRecord::accessFilter());
1001dfb2cda2SGreg Roach    }
1002dfb2cda2SGreg Roach
1003dfb2cda2SGreg Roach    /**
100432cd2800SGreg Roach     * Paginate a search query.
100532cd2800SGreg Roach     *
100632cd2800SGreg Roach     * @param Builder $query      Searches the database for the desired records.
100732cd2800SGreg Roach     * @param Closure $row_mapper Converts a row from the query into a record.
1008a7a24840SGreg Roach     * @param Closure $row_filter
100932cd2800SGreg Roach     * @param int     $offset     Skip this many rows.
101032cd2800SGreg Roach     * @param int     $limit      Take this many rows.
101132cd2800SGreg Roach     *
101236779af1SGreg Roach     * @return Collection<int,mixed>
101332cd2800SGreg Roach     */
1014a7a24840SGreg Roach    private function paginateQuery(Builder $query, Closure $row_mapper, Closure $row_filter, int $offset, int $limit): Collection
101532cd2800SGreg Roach    {
101632cd2800SGreg Roach        $collection = new Collection();
101732cd2800SGreg Roach
101832cd2800SGreg Roach        foreach ($query->cursor() as $row) {
101932cd2800SGreg Roach            $record = $row_mapper($row);
10208aaf5f58SGreg Roach            // searchIndividualNames() and searchFamilyNames() can return duplicate rows,
10218aaf5f58SGreg Roach            // where individuals have multiple names - and we need to sort results by name.
10228aaf5f58SGreg Roach            if ($collection->containsStrict($record)) {
10238aaf5f58SGreg Roach                continue;
10248aaf5f58SGreg Roach            }
1025b68caec6SGreg Roach            // If the object has a method "canShow()", then use it to filter for privacy.
1026a7a24840SGreg Roach            if ($row_filter($record)) {
102732cd2800SGreg Roach                if ($offset > 0) {
102832cd2800SGreg Roach                    $offset--;
102932cd2800SGreg Roach                } else {
103032cd2800SGreg Roach                    if ($limit > 0) {
103132cd2800SGreg Roach                        $collection->push($record);
103232cd2800SGreg Roach                    }
103332cd2800SGreg Roach
103432cd2800SGreg Roach                    $limit--;
103532cd2800SGreg Roach
103632cd2800SGreg Roach                    if ($limit === 0) {
103732cd2800SGreg Roach                        break;
103832cd2800SGreg Roach                    }
103932cd2800SGreg Roach                }
104032cd2800SGreg Roach            }
104132cd2800SGreg Roach        }
104232cd2800SGreg Roach
1043e0458bdcSGreg Roach
104432cd2800SGreg Roach        return $collection;
104532cd2800SGreg Roach    }
1046a7a24840SGreg Roach
1047a7a24840SGreg Roach    /**
1048a7a24840SGreg Roach     * Apply search filters to a SQL query column.  Apply collation rules to MySQL.
1049a7a24840SGreg Roach     *
1050a7a24840SGreg Roach     * @param Builder           $query
1051a7a24840SGreg Roach     * @param Expression|string $field
105209482a55SGreg Roach     * @param array<string>     $search_terms
1053a7a24840SGreg Roach     */
1054a7a24840SGreg Roach    private function whereSearch(Builder $query, $field, array $search_terms): void
1055a7a24840SGreg Roach    {
1056a7a24840SGreg Roach        if ($field instanceof Expression) {
1057a7a24840SGreg Roach            $field = $field->getValue();
1058a7a24840SGreg Roach        }
1059a7a24840SGreg Roach
1060a7a24840SGreg Roach        foreach ($search_terms as $search_term) {
1061b5961194SGreg Roach            $query->where(new Expression($field), 'LIKE', '%' . addcslashes($search_term, '\\%_') . '%');
1062a7a24840SGreg Roach        }
1063a7a24840SGreg Roach    }
1064a7a24840SGreg Roach
1065a7a24840SGreg Roach    /**
10662d686e68SGreg Roach     * Apply soundex search filters to a SQL query column.
10672d686e68SGreg Roach     *
10682d686e68SGreg Roach     * @param Builder           $query
10692d686e68SGreg Roach     * @param Expression|string $field
10702d686e68SGreg Roach     * @param string            $soundex
10712d686e68SGreg Roach     */
10722d686e68SGreg Roach    private function wherePhonetic(Builder $query, $field, string $soundex): void
10732d686e68SGreg Roach    {
10742d686e68SGreg Roach        if ($soundex !== '') {
10750b5fd0a6SGreg Roach            $query->where(static function (Builder $query) use ($soundex, $field): void {
10762d686e68SGreg Roach                foreach (explode(':', $soundex) as $sdx) {
10772d686e68SGreg Roach                    $query->orWhere($field, 'LIKE', '%' . $sdx . '%');
10782d686e68SGreg Roach                }
10792d686e68SGreg Roach            });
10802d686e68SGreg Roach        }
10812d686e68SGreg Roach    }
10822d686e68SGreg Roach
10832d686e68SGreg Roach    /**
1084a7a24840SGreg Roach     * @param Builder     $query
1085a7a24840SGreg Roach     * @param string      $tree_id_field
108609482a55SGreg Roach     * @param array<Tree> $trees
1087a7a24840SGreg Roach     */
1088a7a24840SGreg Roach    private function whereTrees(Builder $query, string $tree_id_field, array $trees): void
1089a7a24840SGreg Roach    {
10900b5fd0a6SGreg Roach        $tree_ids = array_map(static function (Tree $tree): int {
1091a7a24840SGreg Roach            return $tree->id();
1092a7a24840SGreg Roach        }, $trees);
1093a7a24840SGreg Roach
1094a7a24840SGreg Roach        $query->whereIn($tree_id_field, $tree_ids);
1095a7a24840SGreg Roach    }
1096a7a24840SGreg Roach
1097d5ad3db0SGreg Roach    /**
1098d5ad3db0SGreg Roach     * Find the media object that uses a particular media file.
1099d5ad3db0SGreg Roach     *
1100d5ad3db0SGreg Roach     * @param string $file
1101d5ad3db0SGreg Roach     *
110209482a55SGreg Roach     * @return array<Media>
1103d5ad3db0SGreg Roach     */
1104d5ad3db0SGreg Roach    public function findMediaObjectsForMediaFile(string $file): array
1105d5ad3db0SGreg Roach    {
1106d5ad3db0SGreg Roach        return DB::table('media')
1107d5ad3db0SGreg Roach            ->join('media_file', static function (JoinClause $join): void {
1108d5ad3db0SGreg Roach                $join
1109d5ad3db0SGreg Roach                    ->on('media_file.m_file', '=', 'media.m_file')
1110d5ad3db0SGreg Roach                    ->on('media_file.m_id', '=', 'media.m_id');
1111d5ad3db0SGreg Roach            })
1112d5ad3db0SGreg Roach            ->join('gedcom_setting', 'media.m_file', '=', 'gedcom_setting.gedcom_id')
1113d5ad3db0SGreg Roach            ->where(new Expression('setting_value || multimedia_file_refn'), '=', $file)
1114d5ad3db0SGreg Roach            ->select(['media.*'])
1115d5ad3db0SGreg Roach            ->distinct()
1116d5ad3db0SGreg Roach            ->get()
1117d5ad3db0SGreg Roach            ->map($this->mediaRowMapper())
1118d5ad3db0SGreg Roach            ->all();
1119d5ad3db0SGreg Roach    }
1120d5ad3db0SGreg Roach
1121a7a24840SGreg Roach    /**
1122a7a24840SGreg Roach     * A closure to filter records by privacy-filtered GEDCOM data.
1123a7a24840SGreg Roach     *
11245d4b7ec2SGreg Roach     * @param array<string> $search_terms
1125a7a24840SGreg Roach     *
1126a7a24840SGreg Roach     * @return Closure
1127a7a24840SGreg Roach     */
1128a7a24840SGreg Roach    private function rawGedcomFilter(array $search_terms): Closure
1129a7a24840SGreg Roach    {
11306c2179e2SGreg Roach        return static function (GedcomRecord $record) use ($search_terms): bool {
1131a7a24840SGreg Roach            // Ignore non-genealogy fields
1132faa5e163SGreg Roach            $gedcom = preg_replace('/\n\d (?:_UID|_WT_USER) .*/', '', $record->gedcom());
1133a7a24840SGreg Roach
1134a7a24840SGreg Roach            // Ignore matches in links
1135a7a24840SGreg Roach            $gedcom = preg_replace('/\n\d ' . Gedcom::REGEX_TAG . '( @' . Gedcom::REGEX_XREF . '@)?/', '', $gedcom);
1136a7a24840SGreg Roach
1137a7a24840SGreg Roach            // Re-apply the filtering
1138a7a24840SGreg Roach            foreach ($search_terms as $search_term) {
1139a7a24840SGreg Roach                if (mb_stripos($gedcom, $search_term) === false) {
1140a7a24840SGreg Roach                    return false;
1141a7a24840SGreg Roach                }
1142a7a24840SGreg Roach            }
1143a7a24840SGreg Roach
1144a7a24840SGreg Roach            return true;
1145a7a24840SGreg Roach        };
1146a7a24840SGreg Roach    }
114752a8ef61SGreg Roach
114852a8ef61SGreg Roach    /**
114952a8ef61SGreg Roach     * Searching for short or common text can give more results than the system can process.
115052a8ef61SGreg Roach     *
115152a8ef61SGreg Roach     * @param int $limit
115252a8ef61SGreg Roach     *
115352a8ef61SGreg Roach     * @return Closure
115452a8ef61SGreg Roach     */
1155645e3037SGreg Roach    private function rowLimiter(int $limit = self::MAX_SEARCH_RESULTS): Closure
115652a8ef61SGreg Roach    {
11576c2179e2SGreg Roach        return static function () use ($limit): void {
115852a8ef61SGreg Roach            static $n = 0;
115952a8ef61SGreg Roach
116052a8ef61SGreg Roach            if (++$n > $limit) {
116152a8ef61SGreg Roach                $message = I18N::translate('The search returned too many results.');
116252a8ef61SGreg Roach
1163d501c45dSGreg Roach                throw new HttpServiceUnavailableException($message);
116452a8ef61SGreg Roach            }
116552a8ef61SGreg Roach        };
116652a8ef61SGreg Roach    }
1167d5ad3db0SGreg Roach
1168d5ad3db0SGreg Roach    /**
1169d5ad3db0SGreg Roach     * Convert a row from any tree in the families table into a family object.
1170d5ad3db0SGreg Roach     *
1171d5ad3db0SGreg Roach     * @return Closure
1172d5ad3db0SGreg Roach     */
1173d5ad3db0SGreg Roach    private function familyRowMapper(): Closure
1174d5ad3db0SGreg Roach    {
1175f70bcff5SGreg Roach        return function (object $row): Family {
1176d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->f_file);
1177d5ad3db0SGreg Roach
11786b9cb339SGreg Roach            return Registry::familyFactory()->mapper($tree)($row);
1179d5ad3db0SGreg Roach        };
1180d5ad3db0SGreg Roach    }
1181d5ad3db0SGreg Roach
1182d5ad3db0SGreg Roach    /**
1183d5ad3db0SGreg Roach     * Convert a row from any tree in the individuals table into an individual object.
1184d5ad3db0SGreg Roach     *
1185d5ad3db0SGreg Roach     * @return Closure
1186d5ad3db0SGreg Roach     */
1187d5ad3db0SGreg Roach    private function individualRowMapper(): Closure
1188d5ad3db0SGreg Roach    {
1189f70bcff5SGreg Roach        return function (object $row): Individual {
1190d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->i_file);
1191d5ad3db0SGreg Roach
11926b9cb339SGreg Roach            return Registry::individualFactory()->mapper($tree)($row);
1193d5ad3db0SGreg Roach        };
1194d5ad3db0SGreg Roach    }
1195d5ad3db0SGreg Roach
1196d5ad3db0SGreg Roach    /**
1197d4ac8227SGreg Roach     * Convert a row from any tree in the media table into a location object.
1198d4ac8227SGreg Roach     *
1199d4ac8227SGreg Roach     * @return Closure
1200d4ac8227SGreg Roach     */
1201d4ac8227SGreg Roach    private function locationRowMapper(): Closure
1202d4ac8227SGreg Roach    {
1203f70bcff5SGreg Roach        return function (object $row): Location {
12049d28ed8bSGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1205d4ac8227SGreg Roach
1206d4ac8227SGreg Roach            return Registry::locationFactory()->mapper($tree)($row);
1207d4ac8227SGreg Roach        };
1208d4ac8227SGreg Roach    }
1209d4ac8227SGreg Roach
1210d4ac8227SGreg Roach    /**
1211d5ad3db0SGreg Roach     * Convert a row from any tree in the media table into an media object.
1212d5ad3db0SGreg Roach     *
1213d5ad3db0SGreg Roach     * @return Closure
1214d5ad3db0SGreg Roach     */
1215d5ad3db0SGreg Roach    private function mediaRowMapper(): Closure
1216d5ad3db0SGreg Roach    {
1217f70bcff5SGreg Roach        return function (object $row): Media {
1218d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->m_file);
1219d5ad3db0SGreg Roach
12206b9cb339SGreg Roach            return Registry::mediaFactory()->mapper($tree)($row);
1221d5ad3db0SGreg Roach        };
1222d5ad3db0SGreg Roach    }
1223d5ad3db0SGreg Roach
1224d5ad3db0SGreg Roach    /**
1225d5ad3db0SGreg Roach     * Convert a row from any tree in the other table into a note object.
1226d5ad3db0SGreg Roach     *
1227d5ad3db0SGreg Roach     * @return Closure
1228d5ad3db0SGreg Roach     */
1229d5ad3db0SGreg Roach    private function noteRowMapper(): Closure
1230d5ad3db0SGreg Roach    {
1231f70bcff5SGreg Roach        return function (object $row): Note {
1232d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1233d5ad3db0SGreg Roach
12346b9cb339SGreg Roach            return Registry::noteFactory()->mapper($tree)($row);
1235d5ad3db0SGreg Roach        };
1236d5ad3db0SGreg Roach    }
1237d5ad3db0SGreg Roach
1238d5ad3db0SGreg Roach    /**
1239d5ad3db0SGreg Roach     * Convert a row from any tree in the other table into a repository object.
1240d5ad3db0SGreg Roach     *
1241d5ad3db0SGreg Roach     * @return Closure
1242d5ad3db0SGreg Roach     */
1243d5ad3db0SGreg Roach    private function repositoryRowMapper(): Closure
1244d5ad3db0SGreg Roach    {
1245f70bcff5SGreg Roach        return function (object $row): Repository {
1246d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1247d5ad3db0SGreg Roach
12486b9cb339SGreg Roach            return Registry::repositoryFactory()->mapper($tree)($row);
1249d5ad3db0SGreg Roach        };
1250d5ad3db0SGreg Roach    }
1251d5ad3db0SGreg Roach
1252d5ad3db0SGreg Roach    /**
1253d5ad3db0SGreg Roach     * Convert a row from any tree in the sources table into a source object.
1254d5ad3db0SGreg Roach     *
1255d5ad3db0SGreg Roach     * @return Closure
1256d5ad3db0SGreg Roach     */
1257d5ad3db0SGreg Roach    private function sourceRowMapper(): Closure
1258d5ad3db0SGreg Roach    {
1259f70bcff5SGreg Roach        return function (object $row): Source {
1260d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->s_file);
1261d5ad3db0SGreg Roach
12626b9cb339SGreg Roach            return Registry::sourceFactory()->mapper($tree)($row);
1263d5ad3db0SGreg Roach        };
1264d5ad3db0SGreg Roach    }
1265d5ad3db0SGreg Roach
1266d5ad3db0SGreg Roach    /**
1267d4ac8227SGreg Roach     * Convert a row from any tree in the other table into a submission object.
1268d4ac8227SGreg Roach     *
1269d4ac8227SGreg Roach     * @return Closure
1270d4ac8227SGreg Roach     */
1271d4ac8227SGreg Roach    private function submissionRowMapper(): Closure
1272d4ac8227SGreg Roach    {
1273f70bcff5SGreg Roach        return function (object $row): Submission {
1274d4ac8227SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1275d4ac8227SGreg Roach
1276d4ac8227SGreg Roach            return Registry::submissionFactory()->mapper($tree)($row);
1277d4ac8227SGreg Roach        };
1278d4ac8227SGreg Roach    }
1279d4ac8227SGreg Roach
1280d4ac8227SGreg Roach    /**
1281d5ad3db0SGreg Roach     * Convert a row from any tree in the other table into a submitter object.
1282d5ad3db0SGreg Roach     *
1283d5ad3db0SGreg Roach     * @return Closure
1284d5ad3db0SGreg Roach     */
1285d5ad3db0SGreg Roach    private function submitterRowMapper(): Closure
1286d5ad3db0SGreg Roach    {
1287f70bcff5SGreg Roach        return function (object $row): Submitter {
1288d5ad3db0SGreg Roach            $tree = $this->tree_service->find((int) $row->o_file);
1289d5ad3db0SGreg Roach
12906b9cb339SGreg Roach            return Registry::submitterFactory()->mapper($tree)($row);
1291d5ad3db0SGreg Roach        };
1292d5ad3db0SGreg Roach    }
129332cd2800SGreg Roach}
1294