]> git.mxchange.org Git - friendica.git/blob - src/Module/Search/Index.php
769d5f90d2a2ee9862097f68bf795b4a43e63e87
[friendica.git] / src / Module / Search / Index.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module\Search;
23
24 use Friendica\Content\Nav;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Widget;
28 use Friendica\Core\Cache\Enum\Duration;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Search;
32 use Friendica\Core\Session;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\Tag;
39 use Friendica\Module\BaseSearch;
40 use Friendica\Network\HTTPException;
41
42 class Index extends BaseSearch
43 {
44         public static function content(array $parameters = [])
45         {
46                 $search = (!empty($_GET['q']) ? trim(rawurldecode($_GET['q'])) : '');
47
48                 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
49                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Public access denied.'));
50                 }
51
52                 if (DI::config()->get('system', 'local_search') && !Session::isAuthenticated()) {
53                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Only logged in users are permitted to perform a search.'));
54                 }
55
56                 if (DI::config()->get('system', 'permit_crawling') && !Session::isAuthenticated()) {
57                         // Default values:
58                         // 10 requests are "free", after the 11th only a call per minute is allowed
59
60                         $free_crawls = intval(DI::config()->get('system', 'free_crawls'));
61                         if ($free_crawls == 0)
62                                 $free_crawls = 10;
63
64                         $crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period'));
65                         if ($crawl_permit_period == 0)
66                                 $crawl_permit_period = 10;
67
68                         $remote = $_SERVER['REMOTE_ADDR'];
69                         $result = DI::cache()->get('remote_search:' . $remote);
70                         if (!is_null($result)) {
71                                 $resultdata = json_decode($result);
72                                 if (($resultdata->time > (time() - $crawl_permit_period)) && ($resultdata->accesses > $free_crawls)) {
73                                         throw new HTTPException\TooManyRequestsException(DI::l10n()->t('Only one search per minute is permitted for not logged in users.'));
74                                 }
75                                 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => $resultdata->accesses + 1]), Duration::HOUR);
76                         } else {
77                                 DI::cache()->set('remote_search:' . $remote, json_encode(['time' => time(), 'accesses' => 1]), Duration::HOUR);
78                         }
79                 }
80
81                 if (local_user()) {
82                         DI::page()['aside'] .= Widget\SavedSearches::getHTML(Search::getSearchPath($search), $search);
83                 }
84
85                 Nav::setSelected('search');
86
87                 $tag = false;
88                 if (!empty($_GET['tag'])) {
89                         $tag = true;
90                         $search = '#' . trim(rawurldecode($_GET['tag']));
91                 }
92
93                 // contruct a wrapper for the search header
94                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [
95                         'name' => 'search-header',
96                         '$title' => DI::l10n()->t('Search'),
97                         '$title_size' => 3,
98                         '$content' => HTML::search($search, 'search-box', false)
99                 ]);
100
101                 if (!$search) {
102                         return $o;
103                 }
104
105                 if (strpos($search, '#') === 0) {
106                         $tag = true;
107                         $search = substr($search, 1);
108                 }
109
110                 self::tryRedirectToProfile($search);
111
112                 if (strpos($search, '@') === 0 || strpos($search, '!') === 0) {
113                         return self::performContactSearch($search);
114                 }
115
116                 self::tryRedirectToPost($search);
117
118                 if (!empty($_GET['search-option'])) {
119                         switch ($_GET['search-option']) {
120                                 case 'fulltext':
121                                         break;
122                                 case 'tags':
123                                         $tag = true;
124                                         break;
125                                 case 'contacts':
126                                         return self::performContactSearch($search, '@');
127                                 case 'forums':
128                                         return self::performContactSearch($search, '!');
129                         }
130                 }
131
132                 // Don't perform a fulltext or tag search on search results that look like an URL
133                 // Tags don't look like an URL and the fulltext search does only work with natural words
134                 if (parse_url($search, PHP_URL_SCHEME) && parse_url($search, PHP_URL_HOST)) {
135                         Logger::info('Skipping tag and fulltext search since the search looks like a URL.', ['q' => $search]);
136                         notice(DI::l10n()->t('No results.'));
137                         return $o;
138                 }
139
140                 $tag = $tag || DI::config()->get('system', 'only_tag_search');
141
142                 // Here is the way permissions work in the search module...
143                 // Only public posts can be shown
144                 // OR your own posts if you are a logged in member
145                 // No items will be shown if the member has a blocked profile wall.
146
147                 if (DI::mode()->isMobile()) {
148                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
149                                 DI::config()->get('system', 'itemspage_network_mobile'));
150                 } else {
151                         $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
152                                 DI::config()->get('system', 'itemspage_network'));
153                 }
154
155                 $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
156
157                 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
158
159                 if ($tag) {
160                         Logger::info('Start tag search.', ['q' => $search]);
161                         $uriids = Tag::getURIIdListByTag($search, local_user(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
162                         $count = Tag::countByTag($search, local_user());
163                 } else {
164                         Logger::info('Start fulltext search.', ['q' => $search]);
165                         $uriids = Post\Content::getURIIdListBySearch($search, local_user(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
166                         $count = Post\Content::countBySearch($search, local_user());
167                 }
168
169                 if (!empty($uriids)) {
170                         $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`))", 0, local_user()];
171                         $condition = DBA::mergeConditions($condition, ['uri-id' => $uriids]);
172                         $params = ['order' => ['id' => true]];
173                         $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
174                 }
175
176                 if (empty($items)) {
177                         if (empty($last_uriid)) {
178                                 notice(DI::l10n()->t('No results.'));
179                         }
180                         return $o;
181                 }
182
183                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
184                         $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
185                         $o .= Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
186                 }
187
188                 if ($tag) {
189                         $title = DI::l10n()->t('Items tagged with: %s', $search);
190                 } else {
191                         $title = DI::l10n()->t('Results for: %s', $search);
192                 }
193
194                 $o .= Renderer::replaceMacros(Renderer::getMarkupTemplate('section_title.tpl'), [
195                         '$title' => $title
196                 ]);
197
198                 Logger::info('Start Conversation.', ['q' => $search]);
199
200                 $o .= DI::conversation()->create($items, 'search', false, false, 'commented', local_user());
201
202                 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
203                         $o .= HTML::scrollLoader();
204                 } else {
205                         $o .= $pager->renderMinimal($count);
206                 }
207
208
209                 return $o;
210         }
211
212         /**
213          * Tries to redirect to a local profile page based on the input.
214          *
215          * This method separates logged in and anonymous users. Logged in users can trigger contact probes to import
216          * non-existing contacts while anonymous users can only trigger a local lookup.
217          *
218          * Formats matched:
219          * - @user@domain
220          * - user@domain
221          * - Any fully-formed URL
222          *
223          * @param string  $search
224          * @throws HTTPException\InternalServerErrorException
225          * @throws \ImagickException
226          */
227         private static function tryRedirectToProfile(string $search)
228         {
229                 $isUrl = !empty(parse_url($search, PHP_URL_SCHEME));
230                 $isAddr = (bool)preg_match('/^@?([a-z0-9.-_]+@[a-z0-9.-_:]+)$/i', trim($search), $matches);
231
232                 if (!$isUrl && !$isAddr) {
233                         return;
234                 }
235
236                 if ($isAddr) {
237                         $search = $matches[1];
238                 }
239
240                 if (local_user()) {
241                         // User-specific contact URL/address search
242                         $contact_id = Contact::getIdForURL($search, local_user());
243                         if (!$contact_id) {
244                                 // User-specific contact URL/address search and probe
245                                 $contact_id = Contact::getIdForURL($search);
246                         }
247                 } else {
248                         // Cheaper local lookup for anonymous users, no probe
249                         if ($isAddr) {
250                                 $contact = Contact::selectFirst(['id'], ['addr' => $search, 'uid' => 0]);
251                         } else {
252                                 $contact = Contact::getByURL($search, null, ['id']) ?: ['id' => 0];
253                         }
254
255                         if (DBA::isResult($contact)) {
256                                 $contact_id = $contact['id'];
257                         }
258                 }
259
260                 if (!empty($contact_id)) {
261                         DI::baseUrl()->redirect('contact/' . $contact_id);
262                 }
263         }
264
265         /**
266          * Fetch/search a post by URL and redirects to its local representation if it was found.
267          *
268          * @param string  $search
269          * @throws HTTPException\InternalServerErrorException
270          */
271         private static function tryRedirectToPost(string $search)
272         {
273                 if (parse_url($search, PHP_URL_SCHEME) == '') {
274                         return;
275                 }
276
277                 if (local_user()) {
278                         // Post URL search
279                         $item_id = Item::fetchByLink($search, local_user());
280                         if (!$item_id) {
281                                 // If the user-specific search failed, we search and probe a public post
282                                 $item_id = Item::fetchByLink($search);
283                         }
284                 } else {
285                         // Cheaper local lookup for anonymous users, no probe
286                         $item_id = Item::searchByLink($search);
287                 }
288
289                 if (!empty($item_id)) {
290                         $item = Post::selectFirst(['guid'], ['id' => $item_id]);
291                         if (DBA::isResult($item)) {
292                                 DI::baseUrl()->redirect('display/' . $item['guid']);
293                         }
294                 }
295         }
296 }