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