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