]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/Mastodon/Search.php
Merge remote-tracking branch 'upstream/2021.12-rc' into remove-obsolete
[friendica.git] / src / Module / Api / Mastodon / Search.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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\Api\Mastodon;
23
24 use Friendica\Core\Protocol;
25 use Friendica\Core\Search as CoreSearch;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Post;
31 use Friendica\Model\Tag;
32 use Friendica\Module\BaseApi;
33 use Friendica\Object\Search\ContactResult;
34
35 /**
36  * @see https://docs.joinmastodon.org/methods/search/
37  */
38 class Search extends BaseApi
39 {
40         /**
41          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
42          */
43         protected function rawContent(array $request = [])
44         {
45                 self::checkAllowedScope(self::SCOPE_READ);
46                 $uid = self::getCurrentUserID();
47
48                 $request = $this->getRequest([
49                         'account_id'         => 0,     // If provided, statuses returned will be authored only by this account
50                         'max_id'             => 0,     // Return results older than this id
51                         'min_id'             => 0,     // Return results immediately newer than this id
52                         'type'               => '',    // Enum(accounts, hashtags, statuses)
53                         'exclude_unreviewed' => false, // Filter out unreviewed tags? Defaults to false. Use true when trying to find trending tags.
54                         'q'                  => '',    // The search query
55                         'resolve'            => false, // Attempt WebFinger lookup. Defaults to false.
56                         'limit'              => 20,    // Maximum number of results to load, per type. Defaults to 20. Max 40.
57                         'offset'             => 0,     // Offset in search results. Used for pagination. Defaults to 0.
58                         'following'          => false, // Only include accounts that the user is following. Defaults to false.
59                 ], $request);
60
61                 if (empty($request['q'])) {
62                         DI::mstdnError()->UnprocessableEntity();
63                 }
64
65                 $limit = min($request['limit'], 40);
66
67                 $result = ['accounts' => [], 'statuses' => [], 'hashtags' => []];
68
69                 if (empty($request['type']) || ($request['type'] == 'accounts')) {
70                         $result['accounts'] = self::searchAccounts($uid, $request['q'], $request['resolve'], $limit, $request['offset'], $request['following']);
71                 }
72                 if ((empty($request['type']) || ($request['type'] == 'statuses')) && (strpos($request['q'], '@') == false)) {
73                         $result['statuses'] = self::searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']);
74                 }
75                 if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) {
76                         $result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']);
77                 }
78
79                 System::jsonExit($result);
80         }
81
82         private static function searchAccounts(int $uid, string $q, bool $resolve, int $limit, int $offset, bool $following)
83         {
84                 $accounts = [];
85
86                 if (!$following) {
87                         if ((strrpos($q, '@') > 0) && $resolve) {
88                                 $results = CoreSearch::getContactsFromProbe($q);
89                         }
90
91                         if (empty($results)) {
92                                 if (DI::config()->get('system', 'poco_local_search')) {
93                                         $results = CoreSearch::getContactsFromLocalDirectory($q, CoreSearch::TYPE_ALL, 0, $limit);
94                                 } elseif (!empty(DI::config()->get('system', 'directory'))) {
95                                         $results = CoreSearch::getContactsFromGlobalDirectory($q, CoreSearch::TYPE_ALL, 1);
96                                 }
97                         }
98                         if (!empty($results)) {
99                                 $counter = 0;
100                                 foreach ($results->getResults() as $result) {
101                                         if (++$counter > $limit) {
102                                                 continue;
103                                         }
104                                         if ($result instanceof ContactResult) {
105                                                 $id = Contact::getIdForURL($result->getUrl(), 0, false);
106
107                                                 $accounts[] = DI::mstdnAccount()->createFromContactId($id, $uid);
108                                         }
109                                 }
110                         }
111                 } else {
112                         $contacts = Contact::searchByName($q, '', $uid);
113
114                         $counter = 0;
115                         foreach ($contacts as $contact) {
116                                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
117                                         continue;
118                                 }
119                                 if (++$counter > $limit) {
120                                         continue;
121                                 }
122                                 $accounts[] = DI::mstdnAccount()->createFromContactId($contact['id'], $uid);
123                         }
124                         DBA::close($contacts);
125                 }
126
127                 return $accounts;
128         }
129
130         private static function searchStatuses(int $uid, string $q, string $account_id, int $max_id, int $min_id, int $limit, int $offset)
131         {
132                 $params = ['order' => ['uri-id' => true], 'limit' => [$offset, $limit]];
133
134                 if (substr($q, 0, 1) == '#') {
135                         $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
136                                 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
137                                 substr($q, 1), 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
138                         $table = 'tag-search-view';
139                 } else {
140                         $condition = ["`uri-id` IN (SELECT `uri-id` FROM `post-content` WHERE MATCH (`title`, `content-warning`, `body`) AGAINST (? IN BOOLEAN MODE))
141                                 AND (`uid` = ? OR (`uid` = ? AND NOT `global`)) AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
142                                 str_replace('@', ' ', $q), 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
143                         $table = 'post-user-view';
144                 }
145
146                 if (!empty($max_id)) {
147                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $max_id]);
148                 }
149
150                 if (!empty($since_id)) {
151                         $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", $since_id]);
152                 }
153
154                 if (!empty($min_id)) {
155                         $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", $min_id]);
156
157                         $params['order'] = ['uri-id'];
158                 }
159
160                 $items = DBA::select($table, ['uri-id'], $condition, $params);
161
162                 $statuses = [];
163                 while ($item = Post::fetch($items)) {
164                         self::setBoundaries($item['uri-id']);
165                         $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid);
166                 }
167                 DBA::close($items);
168
169                 if (!empty($min_id)) {
170                         $statuses = array_reverse($statuses);
171                 }
172
173                 self::setLinkHeader();
174                 return $statuses;
175         }
176
177         private static function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version)
178         {
179                 $q = ltrim($q, '#');
180
181                 $params = ['order' => ['name'], 'limit' => [$offset, $limit]];
182
183                 $condition = ["EXISTS(SELECT `tid` FROM `post-tag` WHERE `type` = ? AND `tid` = `id`) AND `name` LIKE ?", Tag::HASHTAG, $q . '%'];
184
185                 $tags = DBA::select('tag', ['name'], $condition, $params);
186
187                 $hashtags = [];
188                 foreach ($tags as $tag) {
189                         if ($version == 1) {
190                                 $hashtags[] = $tag['name'];
191                         } else {
192                                 $hashtags[] = new \Friendica\Object\Api\Mastodon\Tag(DI::baseUrl(), $tag);
193                         }
194                 }
195
196                 return $hashtags;
197         }
198 }