3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module\Api\Mastodon;
24 use Friendica\Core\Protocol;
25 use Friendica\Core\System;
26 use Friendica\Database\DBA;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Item;
30 use Friendica\Model\Post;
31 use Friendica\Model\Tag;
32 use Friendica\Module\BaseApi;
33 use Friendica\Util\Network;
36 * @see https://docs.joinmastodon.org/methods/search/
38 class Search extends BaseApi
41 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
43 protected function rawContent(array $request = [])
45 self::checkAllowedScope(self::SCOPE_READ);
46 $uid = self::getCurrentUserID();
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.
61 if (empty($request['q'])) {
62 DI::mstdnError()->UnprocessableEntity();
65 $limit = min($request['limit'], 40);
67 $result = ['accounts' => [], 'statuses' => [], 'hashtags' => []];
69 if (empty($request['type']) || ($request['type'] == 'accounts')) {
70 $result['accounts'] = self::searchAccounts($uid, $request['q'], $request['resolve'], $limit, $request['offset'], $request['following']);
72 if (!is_array($result['accounts'])) {
73 // Curbing the search if we got an exact result
74 $request['type'] = 'accounts';
75 $result['accounts'] = [$result['accounts']];
79 if ((empty($request['type']) || ($request['type'] == 'statuses')) && (strpos($request['q'], '@') == false)) {
80 $result['statuses'] = self::searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']);
82 if (!is_array($result['statuses'])) {
83 // Curbing the search if we got an exact result
84 $request['type'] = 'statuses';
85 $result['statuses'] = [$result['statuses']];
89 if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) {
90 $result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']);
93 System::jsonExit($result);
99 * @param bool $resolve
102 * @param bool $following
103 * @return array|\Friendica\Object\Api\Mastodon\Account Object if result is absolute (exact account match), list if not
104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
105 * @throws \Friendica\Network\HTTPException\NotFoundException
106 * @throws \ImagickException
108 private static function searchAccounts(int $uid, string $q, bool $resolve, int $limit, int $offset, bool $following)
111 (strrpos($q, '@') > 0 || Network::isValidHttpUrl($q))
112 && $id = Contact::getIdForURL($q, 0, $resolve ? null : false)
114 return DI::mstdnAccount()->createFromContactId($id, $uid);
118 foreach (Contact::searchByName($q, '', $following ? $uid : 0, $limit, $offset) as $contact) {
119 $accounts[] = DI::mstdnAccount()->createFromContactId($contact['id'], $uid);
128 * @param string $account_id
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
138 private static function searchStatuses(int $uid, string $q, string $account_id, int $max_id, int $min_id, int $limit, int $offset)
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);
149 $params = ['order' => ['uri-id' => true], 'limit' => [$offset, $limit]];
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';
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';
163 if (!empty($max_id)) {
164 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $max_id]);
167 if (!empty($since_id)) {
168 $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", $since_id]);
171 if (!empty($min_id)) {
172 $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", $min_id]);
174 $params['order'] = ['uri-id'];
177 $items = DBA::select($table, ['uri-id'], $condition, $params);
180 while ($item = Post::fetch($items)) {
181 self::setBoundaries($item['uri-id']);
182 $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid);
186 if (!empty($min_id)) {
187 $statuses = array_reverse($statuses);
190 self::setLinkHeader();
194 private static function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version): array
198 $params = ['order' => ['name'], 'limit' => [$offset, $limit]];
200 $condition = ["`id` IN (SELECT `tid` FROM `post-tag` WHERE `type` = ?) AND `name` LIKE ?", Tag::HASHTAG, $q . '%'];
202 $tags = DBA::select('tag', ['name'], $condition, $params);
205 foreach ($tags as $tag) {
207 $hashtags[] = $tag['name'];
209 $hashtags[] = new \Friendica\Object\Api\Mastodon\Tag(DI::baseUrl(), $tag);