xref: /webtrees/app/Http/RequestHandlers/SearchGeneralPage.php (revision 89f7189b61a494347591c99bdb92afb7d8b66e1b)
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\Services\SearchService;
26use Fisharebest\Webtrees\Services\TreeService;
27use Fisharebest\Webtrees\Site;
28use Fisharebest\Webtrees\Tree;
29use Illuminate\Support\Collection;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Server\RequestHandlerInterface;
33
34use function array_filter;
35use function assert;
36use function in_array;
37use function preg_replace;
38use function redirect;
39use function trim;
40
41use const PREG_SET_ORDER;
42
43/**
44 * Search for genealogy data
45 */
46class SearchGeneralPage implements RequestHandlerInterface
47{
48    use ViewResponseTrait;
49
50    /** @var SearchService */
51    private $search_service;
52
53    /** @var TreeService */
54    private $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_repositories = (bool) ($params['search_repositories'] ?? false);
87        $search_sources      = (bool) ($params['search_sources'] ?? false);
88        $search_notes        = (bool) ($params['search_notes'] ?? false);
89
90        // Default to families and individuals only
91        if (!$search_individuals && !$search_families && !$search_repositories && !$search_sources && !$search_notes) {
92            $search_families    = true;
93            $search_individuals = true;
94        }
95
96        // What to search for?
97        $search_terms = $this->extractSearchTerms($query);
98
99        // What trees to search?
100        if (Site::getPreference('ALLOW_CHANGE_GEDCOM') === '1') {
101            $all_trees = $this->tree_service->all()->all();
102        } else {
103            $all_trees = [$tree];
104        }
105
106        $search_tree_names = $params['search_trees'] ?? [];
107
108        $search_trees = array_filter($all_trees, static function (Tree $tree) use ($search_tree_names): bool {
109            return in_array($tree->name(), $search_tree_names, true);
110        });
111
112        if ($search_trees === []) {
113            $search_trees = [$tree];
114        }
115
116        // Do the search
117        $individuals  = new Collection();
118        $families     = new Collection();
119        $repositories = new Collection();
120        $sources      = new Collection();
121        $notes        = new Collection();
122
123        if ($search_terms !== []) {
124            if ($search_individuals) {
125                $individuals = $this->search_service->searchIndividuals($search_trees, $search_terms);
126            }
127
128            if ($search_families) {
129                $tmp1 = $this->search_service->searchFamilies($search_trees, $search_terms);
130                $tmp2 = $this->search_service->searchFamilyNames($search_trees, $search_terms);
131
132                $families = $tmp1->merge($tmp2)->unique(static function (Family $family): string {
133                    return $family->xref() . '@' . $family->tree()->id();
134                });
135            }
136
137            if ($search_repositories) {
138                $repositories = $this->search_service->searchRepositories($search_trees, $search_terms);
139            }
140
141            if ($search_sources) {
142                $sources = $this->search_service->searchSources($search_trees, $search_terms);
143            }
144
145            if ($search_notes) {
146                $notes = $this->search_service->searchNotes($search_trees, $search_terms);
147            }
148        }
149
150        // If only 1 item is returned, automatically forward to that item
151        if ($individuals->count() === 1 && $families->isEmpty() && $sources->isEmpty() && $notes->isEmpty()) {
152            return redirect($individuals->first()->url());
153        }
154
155        if ($individuals->isEmpty() && $families->count() === 1 && $sources->isEmpty() && $notes->isEmpty()) {
156            return redirect($families->first()->url());
157        }
158
159        if ($individuals->isEmpty() && $families->isEmpty() && $sources->count() === 1 && $notes->isEmpty()) {
160            return redirect($sources->first()->url());
161        }
162
163        if ($individuals->isEmpty() && $families->isEmpty() && $sources->isEmpty() && $notes->count() === 1) {
164            return redirect($notes->first()->url());
165        }
166
167        $title = I18N::translate('General search');
168
169        return $this->viewResponse('search-general-page', [
170            'all_trees'           => $all_trees,
171            'families'            => $families,
172            'individuals'         => $individuals,
173            'notes'               => $notes,
174            'query'               => $query,
175            'repositories'        => $repositories,
176            'search_families'     => $search_families,
177            'search_individuals'  => $search_individuals,
178            'search_notes'        => $search_notes,
179            'search_repositories' => $search_repositories,
180            'search_sources'      => $search_sources,
181            'search_trees'        => $search_trees,
182            'sources'             => $sources,
183            'title'               => $title,
184            'tree'                => $tree,
185        ]);
186    }
187
188    /**
189     * Convert the query into an array of search terms
190     *
191     * @param string $query
192     *
193     * @return string[]
194     */
195    private function extractSearchTerms(string $query): array
196    {
197        $search_terms = [];
198
199        // Words in double quotes stay together
200        preg_match_all('/"([^"]+)"/', $query, $matches, PREG_SET_ORDER);
201        foreach ($matches as $match) {
202            $search_terms[] = trim($match[1]);
203            // Remove this string from the search query
204            $query = strtr($query, [$match[0] => '']);
205        }
206
207        // Treat CJK characters as separate words, not as characters.
208        $query = preg_replace('/\p{Han}/u', '$0 ', $query);
209
210        // Other words get treated separately
211        preg_match_all('/[\S]+/', $query, $matches, PREG_SET_ORDER);
212        foreach ($matches as $match) {
213            $search_terms[] = $match[0];
214        }
215
216        return $search_terms;
217    }
218}
219