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