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