]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/Mastodon/Search.php
Merge pull request #12837 from HankG/fix-blocks-ignores-in-full-context-status-request
[friendica.git] / src / Module / Api / Mastodon / Search.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Item;
31 use Friendica\Model\Post;
32 use Friendica\Model\Tag;
33 use Friendica\Module\BaseApi;
34 use Friendica\Util\Network;
35
36 /**
37  * @see https://docs.joinmastodon.org/methods/search/
38  */
39 class Search extends BaseApi
40 {
41         /**
42          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
43          */
44         protected function rawContent(array $request = [])
45         {
46                 self::checkAllowedScope(self::SCOPE_READ);
47                 $uid = self::getCurrentUserID();
48
49                 $request = $this->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                 ], $request);
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 (!is_array($result['accounts'])) {
74                                 // Curbing the search if we got an exact result
75                                 $request['type'] = 'accounts';
76                                 $result['accounts'] = [$result['accounts']];
77                         }
78                 }
79
80                 if (empty($request['type']) || ($request['type'] == 'statuses')) {
81                         $result['statuses'] = self::searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']);
82
83                         if (!is_array($result['statuses'])) {
84                                 // Curbing the search if we got an exact result
85                                 $request['type'] = 'statuses';
86                                 $result['statuses'] = [$result['statuses']];
87                         }
88                 }
89
90                 if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) {
91                         $result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']);
92                 }
93
94                 System::jsonExit($result);
95         }
96
97         /**
98          * @param int    $uid
99          * @param string $q
100          * @param bool   $resolve
101          * @param int    $limit
102          * @param int    $offset
103          * @param bool   $following
104          * @return array|\Friendica\Object\Api\Mastodon\Account Object if result is absolute (exact account match), list if not
105          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106          * @throws \Friendica\Network\HTTPException\NotFoundException
107          * @throws \ImagickException
108          */
109         private static function searchAccounts(int $uid, string $q, bool $resolve, int $limit, int $offset, bool $following)
110         {
111                 if (($offset == 0) && (strrpos($q, '@') > 0 || Network::isValidHttpUrl($q))
112                         && $id = Contact::getIdForURL($q, 0, $resolve ? null : false)
113                 ) {
114                         return DI::mstdnAccount()->createFromContactId($id, $uid);
115                 }
116
117                 $accounts = [];
118                 foreach (Contact::searchByName($q, '', $following ? $uid : 0, $limit, $offset) as $contact) {
119                         $accounts[] = DI::mstdnAccount()->createFromContactId($contact['id'], $uid);
120                 }
121
122                 return $accounts;
123         }
124
125         /**
126          * @param int    $uid
127          * @param string $q
128          * @param string $account_id
129          * @param int    $max_id
130          * @param int    $min_id
131          * @param int    $limit
132          * @param int    $offset
133          * @return array|\Friendica\Object\Api\Mastodon\Status Object is result is absolute (exact post match), list if not
134          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
135          * @throws \Friendica\Network\HTTPException\NotFoundException
136          * @throws \ImagickException
137          */
138         private static function searchStatuses(int $uid, string $q, string $account_id, int $max_id, int $min_id, int $limit, int $offset)
139         {
140                 if (Network::isValidHttpUrl($q)) {
141                         $q = Network::convertToIdn($q);
142                         // If the user-specific search failed, we search and probe a public post
143                         $item_id = Item::fetchByLink($q, $uid) ?: Item::fetchByLink($q);
144                         if ($item_id && $item = Post::selectFirst(['uri-id'], ['id' => $item_id])) {
145                                 return DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, self::appSupportsQuotes());
146                         }
147                 }
148
149                 $params = ['order' => ['uri-id' => true], 'limit' => [$offset, $limit]];
150
151                 if (substr($q, 0, 1) == '#') {
152                         $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
153                                 AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
154                                 substr($q, 1), 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
155                         $table = 'tag-search-view';
156                 } else {
157                         $condition = ["`uri-id` IN (SELECT `uri-id` FROM `post-content` WHERE MATCH (`title`, `content-warning`, `body`) AGAINST (? IN BOOLEAN MODE))
158                                 AND (`uid` = ? OR (`uid` = ? AND NOT `global`)) AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
159                                 str_replace('@', ' ', $q), 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0];
160                         $table = 'post-user-view';
161                 }
162
163                 if (!empty($max_id)) {
164                         $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $max_id]);
165                 }
166
167                 if (!empty($since_id)) {
168                         $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", $since_id]);
169                 }
170
171                 if (!empty($min_id)) {
172                         $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", $min_id]);
173
174                         $params['order'] = ['uri-id'];
175                 }
176
177                 $items = DBA::select($table, ['uri-id'], $condition, $params);
178
179                 $display_quotes = self::appSupportsQuotes();
180
181                 $statuses = [];
182                 while ($item = Post::fetch($items)) {
183                         self::setBoundaries($item['uri-id']);
184                         try {
185                                 $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
186                         } catch (\Throwable $th) {
187                                 Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
188                         }
189                 }
190                 DBA::close($items);
191
192                 if (!empty($min_id)) {
193                         $statuses = array_reverse($statuses);
194                 }
195
196                 self::setLinkHeader();
197                 return $statuses;
198         }
199
200         private static function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version): array
201         {
202                 $q = ltrim($q, '#');
203
204                 $params = ['order' => ['name'], 'limit' => [$offset, $limit]];
205
206                 $condition = ["`id` IN (SELECT `tid` FROM `post-tag` WHERE `type` = ?) AND `name` LIKE ?", Tag::HASHTAG, $q . '%'];
207
208                 $tags = DBA::select('tag', ['name'], $condition, $params);
209
210                 $hashtags = [];
211                 foreach ($tags as $tag) {
212                         if ($version == 1) {
213                                 $hashtags[] = $tag['name'];
214                         } else {
215                                 $hashtags[] = new \Friendica\Object\Api\Mastodon\Tag(DI::baseUrl(), $tag);
216                         }
217                 }
218
219                 return $hashtags;
220         }
221 }