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