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