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