xref: /webtrees/app/Http/RequestHandlers/SearchGeneralPage.php (revision 97b27c9d9d4f843b25c3c6cac61d040ef709d4ae)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\Http\ViewResponseTrait;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Services\SearchService;
25use Fisharebest\Webtrees\Services\TreeService;
26use Fisharebest\Webtrees\Site;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Support\Collection;
29use Psr\Http\Message\ResponseInterface;
30use Psr\Http\Message\ServerRequestInterface;
31use Psr\Http\Server\RequestHandlerInterface;
32
33use function array_filter;
34use function assert;
35use function in_array;
36use function preg_match;
37use function preg_replace;
38use function redirect;
39use function str_replace;
40use function trim;
41
42/**
43 * Search for genealogy data
44 */
45class SearchGeneralPage implements RequestHandlerInterface
46{
47    use ViewResponseTrait;
48
49    /** @var SearchService */
50    private $search_service;
51
52    /** @var TreeService */
53    private $tree_service;
54
55    /**
56     * SearchController constructor.
57     *
58     * @param SearchService $search_service
59     * @param TreeService   $tree_service
60     */
61    public function __construct(SearchService $search_service, TreeService $tree_service)
62    {
63        $this->search_service = $search_service;
64        $this->tree_service   = $tree_service;
65    }
66
67    /**
68     * The standard search.
69     *
70     * @param ServerRequestInterface $request
71     *
72     * @return ResponseInterface
73     */
74    public function handle(ServerRequestInterface $request): ResponseInterface
75    {
76        $tree = $request->getAttribute('tree');
77        assert($tree instanceof Tree);
78
79        $params = $request->getQueryParams();
80        $query  = $params['query'] ?? '';
81
82        // What type of records to search?
83        $search_individuals  = (bool) ($params['search_individuals'] ?? false);
84        $search_families     = (bool) ($params['search_families'] ?? false);
85        $search_repositories = (bool) ($params['search_repositories'] ?? false);
86        $search_sources      = (bool) ($params['search_sources'] ?? false);
87        $search_notes        = (bool) ($params['search_notes'] ?? false);
88
89        // Default to families and individuals only
90        if (!$search_individuals && !$search_families && !$search_repositories && !$search_sources && !$search_notes) {
91            $search_families    = true;
92            $search_individuals = true;
93        }
94
95        // What to search for?
96        $search_terms = $this->extractSearchTerms($query);
97
98        // What trees to seach?
99        if (Site::getPreference('ALLOW_CHANGE_GEDCOM') === '1') {
100            $all_trees = $this->tree_service->all()->all();
101        } else {
102            $all_trees = [$tree];
103        }
104
105        $search_tree_names = $params['search_trees'] ?? [];
106
107        $search_trees = array_filter($all_trees, static function (Tree $tree) use ($search_tree_names): bool {
108            return in_array($tree->name(), $search_tree_names, true);
109        });
110
111        if ($search_trees === []) {
112            $search_trees = [$tree];
113        }
114
115        // Do the search
116        $individuals  = new Collection();
117        $families     = new Collection();
118        $repositories = new Collection();
119        $sources      = new Collection();
120        $notes        = new Collection();
121
122        if ($search_terms !== []) {
123            if ($search_individuals) {
124                $individuals = $this->search_service->searchIndividuals($search_trees, $search_terms);
125            }
126
127            if ($search_families) {
128                $tmp1 = $this->search_service->searchFamilies($search_trees, $search_terms);
129                $tmp2 = $this->search_service->searchFamilyNames($search_trees, $search_terms);
130
131                $families = $tmp1->merge($tmp2)->unique();
132            }
133
134            if ($search_repositories) {
135                $repositories = $this->search_service->searchRepositories($search_trees, $search_terms);
136            }
137
138            if ($search_sources) {
139                $sources = $this->search_service->searchSources($search_trees, $search_terms);
140            }
141
142            if ($search_notes) {
143                $notes = $this->search_service->searchNotes($search_trees, $search_terms);
144            }
145        }
146
147        // If only 1 item is returned, automatically forward to that item
148        if ($individuals->count() === 1 && $families->isEmpty() && $sources->isEmpty() && $notes->isEmpty()) {
149            return redirect($individuals->first()->url());
150        }
151
152        if ($individuals->isEmpty() && $families->count() === 1 && $sources->isEmpty() && $notes->isEmpty()) {
153            return redirect($families->first()->url());
154        }
155
156        if ($individuals->isEmpty() && $families->isEmpty() && $sources->count() === 1 && $notes->isEmpty()) {
157            return redirect($sources->first()->url());
158        }
159
160        if ($individuals->isEmpty() && $families->isEmpty() && $sources->isEmpty() && $notes->count() === 1) {
161            return redirect($notes->first()->url());
162        }
163
164        $title = I18N::translate('General search');
165
166        return $this->viewResponse('search-general-page', [
167            'all_trees'           => $all_trees,
168            'families'            => $families,
169            'individuals'         => $individuals,
170            'notes'               => $notes,
171            'query'               => $query,
172            'repositories'        => $repositories,
173            'search_families'     => $search_families,
174            'search_individuals'  => $search_individuals,
175            'search_notes'        => $search_notes,
176            'search_repositories' => $search_repositories,
177            'search_sources'      => $search_sources,
178            'search_trees'        => $search_trees,
179            'sources'             => $sources,
180            'title'               => $title,
181            'tree'                => $tree,
182        ]);
183    }
184
185    /**
186     * Convert the query into an array of search terms
187     *
188     * @param string $query
189     *
190     * @return string[]
191     */
192    private function extractSearchTerms(string $query): array
193    {
194        $search_terms = [];
195
196        // Words in double quotes stay together
197        while (preg_match('/"([^"]+)"/', $query, $match)) {
198            $search_terms[] = trim($match[1]);
199            $query          = str_replace($match[0], '', $query);
200        }
201
202        // Treat CJK characters as separate words, not as characters.
203        $query = preg_replace('/\p{Han}/u', '$0 ', $query);
204
205        // Other words get treated separately
206        while (preg_match('/[\S]+/', $query, $match)) {
207            $search_terms[] = trim($match[0]);
208            $query          = str_replace($match[0], '', $query);
209        }
210
211        return $search_terms;
212    }
213}
214