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