xref: /webtrees/app/Http/RequestHandlers/SearchGeneralPage.php (revision 058ba7243339e0f2f5f84aa0f772e56ee5252797)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Family;
23use Fisharebest\Webtrees\Http\ViewResponseTrait;
24use Fisharebest\Webtrees\I18N;
25use Fisharebest\Webtrees\Location;
26use Fisharebest\Webtrees\Note;
27use Fisharebest\Webtrees\Repository;
28use Fisharebest\Webtrees\Services\SearchService;
29use Fisharebest\Webtrees\Services\TreeService;
30use Fisharebest\Webtrees\Site;
31use Fisharebest\Webtrees\Tree;
32use Illuminate\Database\Capsule\Manager as DB;
33use Illuminate\Support\Collection;
34use Psr\Http\Message\ResponseInterface;
35use Psr\Http\Message\ServerRequestInterface;
36use Psr\Http\Server\RequestHandlerInterface;
37
38use function assert;
39use function preg_replace;
40use function redirect;
41use function trim;
42
43use const PREG_SET_ORDER;
44
45/**
46 * Search for genealogy data
47 */
48class SearchGeneralPage implements RequestHandlerInterface
49{
50    use ViewResponseTrait;
51
52    private SearchService $search_service;
53
54    private TreeService $tree_service;
55
56    /**
57     * SearchController constructor.
58     *
59     * @param SearchService $search_service
60     * @param TreeService   $tree_service
61     */
62    public function __construct(SearchService $search_service, TreeService $tree_service)
63    {
64        $this->search_service = $search_service;
65        $this->tree_service   = $tree_service;
66    }
67
68    /**
69     * The standard search.
70     *
71     * @param ServerRequestInterface $request
72     *
73     * @return ResponseInterface
74     */
75    public function handle(ServerRequestInterface $request): ResponseInterface
76    {
77        $tree = $request->getAttribute('tree');
78        assert($tree instanceof Tree);
79
80        $params = $request->getQueryParams();
81        $query  = $params['query'] ?? '';
82
83        // What type of records to search?
84        $search_individuals  = (bool) ($params['search_individuals'] ?? false);
85        $search_families     = (bool) ($params['search_families'] ?? false);
86        $search_locations    = (bool) ($params['search_locations'] ?? false);
87        $search_repositories = (bool) ($params['search_repositories'] ?? false);
88        $search_sources      = (bool) ($params['search_sources'] ?? false);
89        $search_notes        = (bool) ($params['search_notes'] ?? false);
90
91        $exist_notes = DB::table('other')
92            ->where('o_file', '=', $tree->id())
93            ->where('o_type', '=', Note::RECORD_TYPE)
94            ->exists();
95
96        $exist_locations = DB::table('other')
97            ->where('o_file', '=', $tree->id())
98            ->where('o_type', '=', Location::RECORD_TYPE)
99            ->exists();
100
101        $exist_repositories = DB::table('other')
102            ->where('o_file', '=', $tree->id())
103            ->where('o_type', '=', Repository::RECORD_TYPE)
104            ->exists();
105
106        $exist_sources = DB::table('sources')
107            ->where('s_file', '=', $tree->id())
108            ->exists();
109
110        // Default to families and individuals only
111        if (!$search_individuals && !$search_families && !$search_repositories && !$search_sources && !$search_notes) {
112            $search_families    = true;
113            $search_individuals = true;
114        }
115
116        // What to search for?
117        $search_terms = $this->extractSearchTerms($query);
118
119        // What trees to search?
120        if (Site::getPreference('ALLOW_CHANGE_GEDCOM') === '1') {
121            $all_trees = $this->tree_service->all();
122        } else {
123            $all_trees = new Collection([$tree]);
124        }
125
126        $search_tree_names = new Collection($params['search_trees'] ?? []);
127
128        $search_trees = $all_trees
129            ->filter(static function (Tree $tree) use ($search_tree_names): bool {
130                return $search_tree_names->containsStrict($tree->name());
131            });
132
133        if ($search_trees->isEmpty()) {
134            $search_trees->add($tree);
135        }
136
137        // Do the search
138        $individuals  = new Collection();
139        $families     = new Collection();
140        $locations    = new Collection();
141        $repositories = new Collection();
142        $sources      = new Collection();
143        $notes        = new Collection();
144
145        if ($search_terms !== []) {
146            if ($search_individuals) {
147                $individuals = $this->search_service->searchIndividuals($search_trees->all(), $search_terms);
148            }
149
150            if ($search_families) {
151                $tmp1 = $this->search_service->searchFamilies($search_trees->all(), $search_terms);
152                $tmp2 = $this->search_service->searchFamilyNames($search_trees->all(), $search_terms);
153
154                $families = $tmp1->merge($tmp2)->unique(static function (Family $family): string {
155                    return $family->xref() . '@' . $family->tree()->id();
156                });
157            }
158
159            if ($search_repositories) {
160                $repositories = $this->search_service->searchRepositories($search_trees->all(), $search_terms);
161            }
162
163            if ($search_sources) {
164                $sources = $this->search_service->searchSources($search_trees->all(), $search_terms);
165            }
166
167            if ($search_notes) {
168                $notes = $this->search_service->searchNotes($search_trees->all(), $search_terms);
169            }
170
171            if ($search_locations) {
172                $locations = $this->search_service->searchLocations($search_trees->all(), $search_terms);
173            }
174        }
175
176        // If only 1 item is returned, automatically forward to that item
177        if ($individuals->count() === 1 && $families->isEmpty() && $sources->isEmpty() && $notes->isEmpty() && $locations->isEmpty()) {
178            return redirect($individuals->first()->url());
179        }
180
181        if ($individuals->isEmpty() && $families->count() === 1 && $sources->isEmpty() && $notes->isEmpty() && $locations->isEmpty()) {
182            return redirect($families->first()->url());
183        }
184
185        if ($individuals->isEmpty() && $families->isEmpty() && $sources->count() === 1 && $notes->isEmpty() && $locations->isEmpty()) {
186            return redirect($sources->first()->url());
187        }
188
189        if ($individuals->isEmpty() && $families->isEmpty() && $sources->isEmpty() && $notes->count() === 1 && $locations->isEmpty()) {
190            return redirect($notes->first()->url());
191        }
192
193        if ($individuals->isEmpty() && $families->isEmpty() && $sources->isEmpty() && $notes->isEmpty() && $locations->count() === 1) {
194            return redirect($locations->first()->url());
195        }
196
197        $title = I18N::translate('General search');
198
199        return $this->viewResponse('search-general-page', [
200            'all_trees'           => $all_trees,
201            'exist_locations'     => $exist_locations,
202            'exist_notes'         => $exist_notes,
203            'exist_repositories'  => $exist_repositories,
204            'exist_sources'       => $exist_sources,
205            'families'            => $families,
206            'individuals'         => $individuals,
207            'locations'           => $locations,
208            'notes'               => $notes,
209            'query'               => $query,
210            'repositories'        => $repositories,
211            'search_families'     => $search_families,
212            'search_individuals'  => $search_individuals,
213            'search_locations'    => $search_locations,
214            'search_notes'        => $search_notes,
215            'search_repositories' => $search_repositories,
216            'search_sources'      => $search_sources,
217            'search_trees'        => $search_trees,
218            'sources'             => $sources,
219            'title'               => $title,
220            'tree'                => $tree,
221        ]);
222    }
223
224    /**
225     * Convert the query into an array of search terms
226     *
227     * @param string $query
228     *
229     * @return array<string>
230     */
231    private function extractSearchTerms(string $query): array
232    {
233        $search_terms = [];
234
235        // Words in double quotes stay together
236        preg_match_all('/"([^"]+)"/', $query, $matches, PREG_SET_ORDER);
237        foreach ($matches as $match) {
238            $search_terms[] = trim($match[1]);
239            // Remove this string from the search query
240            $query = strtr($query, [$match[0] => '']);
241        }
242
243        // Treat CJK characters as separate words, not as characters.
244        $query = preg_replace('/\p{Han}/u', '$0 ', $query);
245
246        // Other words get treated separately
247        preg_match_all('/[\S]+/', $query, $matches, PREG_SET_ORDER);
248        foreach ($matches as $match) {
249            $search_terms[] = $match[0];
250        }
251
252        return $search_terms;
253    }
254}
255