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