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