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