]> git.mxchange.org Git - friendica.git/blob - src/Module/Api/Mastodon/Statuses.php
Update src/Module/Api/Mastodon/Statuses.php
[friendica.git] / src / Module / Api / Mastodon / Statuses.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\Content\Text\Markdown;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Core\Worker;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Group;
32 use Friendica\Model\Item;
33 use Friendica\Model\Photo;
34 use Friendica\Model\Post;
35 use Friendica\Model\User;
36 use Friendica\Module\BaseApi;
37 use Friendica\Network\HTTPException;
38 use Friendica\Protocol\Activity;
39 use Friendica\Util\Images;
40
41 /**
42  * @see https://docs.joinmastodon.org/methods/statuses/
43  */
44 class Statuses extends BaseApi
45 {
46         public function put(array $request = [])
47         {
48                 self::checkAllowedScope(self::SCOPE_WRITE);
49                 $uid = self::getCurrentUserID();
50
51                 $request = $this->getRequest([
52                         'status'         => '',    // Text content of the status. If media_ids is provided, this becomes optional. Attaching a poll is optional while status is provided.
53                         'in_reply_to_id' => 0,     // ID of the status being replied to, if status is a reply
54                         'spoiler_text'   => '',    // Text to be shown as a warning or subject before the actual content. Statuses are generally collapsed behind this field.
55                         'language'       => '',    // ISO 639 language code for this status.
56                 ], $request);
57
58                 $owner = User::getOwnerDataById($uid);
59
60                 $condition = [
61                         'uid'        => $uid,
62                         'uri-id'     => $this->parameters['id'],
63                         'contact-id' => $owner['id'],
64                         'author-id'  => Contact::getPublicIdByUserId($uid),
65                         'origin'     => true,
66                 ];
67
68                 $post = Post::selectFirst(['uri-id', 'id'], $condition);
69                 if (empty($post['id'])) {
70                         throw new HTTPException\NotFoundException('Item with URI ID ' . $this->parameters['id'] . ' not found for user ' . $uid . '.');
71                 }
72
73                 // The imput is defined as text. So we can use Markdown for some enhancements
74                 $item = ['body' => Markdown::toBBCode($request['status']), 'app' => $this->getApp(), 'title' => ''];
75
76                 if (!empty($request['language'])) {
77                         $item['language'] = json_encode([$request['language'] => 1]);
78                 }
79
80                 if (!empty($request['spoiler_text'])) {
81                         if (($request['in_reply_to_id'] == $post['uri-id']) && DI::pConfig()->get($uid, 'system', 'api_spoiler_title', true)) {
82                                 $item['title'] = $request['spoiler_text'];
83                         } else {
84                                 $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $request['spoiler_text'] . "[/abstract]\n" . $item['body'];
85                         }
86                 }
87
88                 Item::update($item, ['id' => $post['id']]);
89                 Item::updateDisplayCache($post['uri-id']);
90
91                 System::jsonExit(DI::mstdnStatus()->createFromUriId($post['uri-id'], $uid, self::appSupportsQuotes()));
92         }
93
94         protected function post(array $request = [])
95         {
96                 self::checkAllowedScope(self::SCOPE_WRITE);
97                 $uid = self::getCurrentUserID();
98
99                 $request = $this->getRequest([
100                         'status'         => '',    // Text content of the status. If media_ids is provided, this becomes optional. Attaching a poll is optional while status is provided.
101                         'media_ids'      => [],    // Array of Attachment ids to be attached as media. If provided, status becomes optional, and poll cannot be used.
102                         'poll'           => [],    // Poll data. If provided, media_ids cannot be used, and poll[expires_in] must be provided.
103                         'in_reply_to_id' => 0,     // ID of the status being replied to, if status is a reply
104                         'quote_id'       => 0,     // ID of the message to quote
105                         'sensitive'      => false, // Mark status and attached media as sensitive?
106                         'spoiler_text'   => '',    // Text to be shown as a warning or subject before the actual content. Statuses are generally collapsed behind this field.
107                         'visibility'     => '',    // Visibility of the posted status. One of: "public", "unlisted", "private" or "direct".
108                         'scheduled_at'   => '',    // ISO 8601 Datetime at which to schedule a status. Providing this paramter will cause ScheduledStatus to be returned instead of Status. Must be at least 5 minutes in the future.
109                         'language'       => '',    // ISO 639 language code for this status.
110                         'friendica'      => [],    // Friendica extensions to the standard Mastodon API spec
111                 ], $request);
112
113                 $owner = User::getOwnerDataById($uid);
114
115                 // The imput is defined as text. So we can use Markdown for some enhancements
116                 $body = Markdown::toBBCode($request['status']);
117
118                 $item               = [];
119                 $item['network']    = Protocol::DFRN;
120                 $item['uid']        = $uid;
121                 $item['verb']       = Activity::POST;
122                 $item['contact-id'] = $owner['id'];
123                 $item['author-id']  = $item['owner-id'] = Contact::getPublicIdByUserId($uid);
124                 $item['title']      = '';
125                 $item['body']       = $body;
126                 $item['app']        = $this->getApp();
127
128                 switch ($request['visibility']) {
129                         case 'public':
130                                 $item['allow_cid'] = '';
131                                 $item['allow_gid'] = '';
132                                 $item['deny_cid']  = '';
133                                 $item['deny_gid']  = '';
134                                 $item['private']   = Item::PUBLIC;
135                                 break;
136                         case 'unlisted':
137                                 $item['allow_cid'] = '';
138                                 $item['allow_gid'] = '';
139                                 $item['deny_cid']  = '';
140                                 $item['deny_gid']  = '';
141                                 $item['private']   = Item::UNLISTED;
142                                 break;
143                         case 'private':
144                                 if (!empty($owner['allow_cid'] . $owner['allow_gid'] . $owner['deny_cid'] . $owner['deny_gid'])) {
145                                         $item['allow_cid'] = $owner['allow_cid'];
146                                         $item['allow_gid'] = $owner['allow_gid'];
147                                         $item['deny_cid']  = $owner['deny_cid'];
148                                         $item['deny_gid']  = $owner['deny_gid'];
149                                 } else {
150                                         $item['allow_cid'] = '';
151                                         $item['allow_gid'] = '<' . Group::FOLLOWERS . '>';
152                                         $item['deny_cid']  = '';
153                                         $item['deny_gid']  = '';
154                                 }
155                                 $item['private'] = Item::PRIVATE;
156                                 break;
157                         case 'direct':
158                                 $item['private'] = Item::PRIVATE;
159                                 // The permissions are assigned in "expandTags"
160                                 break;
161                         default:
162                                 if (is_numeric($request['visibility']) && Group::exists($request['visibility'], $uid)) {
163                                         $item['allow_cid'] = '';
164                                         $item['allow_gid'] = '<' . $request['visibility'] . '>';
165                                         $item['deny_cid']  = '';
166                                         $item['deny_gid']  = '';
167                                 } else {
168                                         $item['allow_cid'] = $owner['allow_cid'];
169                                         $item['allow_gid'] = $owner['allow_gid'];
170                                         $item['deny_cid']  = $owner['deny_cid'];
171                                         $item['deny_gid']  = $owner['deny_gid'];
172                                 }
173
174                                 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
175                                         $item['private'] = Item::PRIVATE;
176                                 } elseif (DI::pConfig()->get($uid, 'system', 'unlisted')) {
177                                         $item['private'] = Item::UNLISTED;
178                                 } else {
179                                         $item['private'] = Item::PUBLIC;
180                                 }
181                                 break;
182                 }
183
184                 if (!empty($request['language'])) {
185                         $item['language'] = json_encode([$request['language'] => 1]);
186                 }
187
188                 if ($request['in_reply_to_id']) {
189                         $parent = Post::selectFirst(['uri', 'private'], ['uri-id' => $request['in_reply_to_id'], 'uid' => [0, $uid]]);
190
191                         $item['thr-parent']  = $parent['uri'];
192                         $item['gravity']     = Item::GRAVITY_COMMENT;
193                         $item['object-type'] = Activity\ObjectType::COMMENT;
194
195                         if (in_array($parent['private'], [Item::UNLISTED, Item::PUBLIC]) && ($item['private'] == Item::PRIVATE)) {
196                                 throw new HTTPException\NotImplementedException('Private replies for public posts are not implemented.');
197                         }
198                 } else {
199                         self::checkThrottleLimit();
200
201                         $item['gravity']     = Item::GRAVITY_PARENT;
202                         $item['object-type'] = Activity\ObjectType::NOTE;
203                 }
204
205                 if ($request['quote_id']) {
206                         if (!Post::exists(['uri-id' => $request['quote_id'], 'uid' => [0, $uid]])) {
207                                 throw new HTTPException\NotFoundException('Item with URI ID ' . $request['quote_id'] . ' not found for user ' . $uid . '.');
208                         }
209                         $item['quote-uri-id'] = $request['quote_id'];
210                 }
211
212                 $item['title'] = $request['friendica']['title'] ?? '';
213
214                 if (!empty($request['spoiler_text'])) {
215                         if (!isset($request['friendica']['title']) && !$request['in_reply_to_id'] && DI::pConfig()->get($uid, 'system', 'api_spoiler_title', true)) {
216                                 $item['title'] = $request['spoiler_text'];
217                         } else {
218                                 $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $request['spoiler_text'] . "[/abstract]\n" . $item['body'];
219                         }
220                 }
221
222                 $item = DI::contentItem()->expandTags($item, $request['visibility'] == 'direct');
223
224                 if (!empty($request['media_ids'])) {
225                         $item['object-type'] = Activity\ObjectType::IMAGE;
226                         $item['post-type']   = Item::PT_IMAGE;
227                         $item['attachments'] = [];
228
229                         foreach ($request['media_ids'] as $id) {
230                                 $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
231                                                 WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
232                                                 ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
233
234                                 if (empty($media)) {
235                                         continue;
236                                 }
237
238                                 Photo::setPermissionForRessource($media[0]['resource-id'], $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
239
240                                 $ressources[] = $media[0]['resource-id'];
241                                 $phototypes = Images::supportedTypes();
242                                 $ext = $phototypes[$media[0]['type']];
243
244                                 $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
245                                         'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
246                                         'size' => $media[0]['datasize'],
247                                         'name' => $media[0]['filename'] ?: $media[0]['resource-id'],
248                                         'description' => $media[0]['desc'] ?? '',
249                                         'width' => $media[0]['width'],
250                                         'height' => $media[0]['height']];
251
252                                 if (count($media) > 1) {
253                                         $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
254                                         $attachment['preview-width'] = $media[1]['width'];
255                                         $attachment['preview-height'] = $media[1]['height'];
256                                 }
257                                 $item['attachments'][] = $attachment;
258                         }
259                 }
260
261                 if (!empty($request['scheduled_at'])) {
262                         $item['guid'] = Item::guid($item, true);
263                         $item['uri'] = Item::newURI($item['guid']);
264                         $id = Post\Delayed::add($item['uri'], $item, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED, $request['scheduled_at']);
265                         if (empty($id)) {
266                                 DI::mstdnError()->InternalError();
267                         }
268                         System::jsonExit(DI::mstdnScheduledStatus()->createFromDelayedPostId($id, $uid)->toArray());
269                 }
270
271                 $id = Item::insert($item, true);
272                 if (!empty($id)) {
273                         $item = Post::selectFirst(['uri-id'], ['id' => $id]);
274                         if (!empty($item['uri-id'])) {
275                                 System::jsonExit(DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, self::appSupportsQuotes()));
276                         }
277                 }
278
279                 DI::mstdnError()->InternalError();
280         }
281
282         protected function delete(array $request = [])
283         {
284                 self::checkAllowedScope(self::SCOPE_READ);
285                 $uid = self::getCurrentUserID();
286
287                 if (empty($this->parameters['id'])) {
288                         DI::mstdnError()->UnprocessableEntity();
289                 }
290
291                 $item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => $uid]);
292                 if (empty($item['id'])) {
293                         DI::mstdnError()->RecordNotFound();
294                 }
295
296                 if (!Item::markForDeletionById($item['id'])) {
297                         DI::mstdnError()->RecordNotFound();
298                 }
299
300                 System::jsonExit([]);
301         }
302
303         /**
304          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
305          */
306         protected function rawContent(array $request = [])
307         {
308                 $uid = self::getCurrentUserID();
309
310                 if (empty($this->parameters['id'])) {
311                         DI::mstdnError()->UnprocessableEntity();
312                 }
313
314                 System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid, self::appSupportsQuotes(), false));
315         }
316
317         private function getApp(): string
318         {
319                 if (!empty(self::getCurrentApplication()['name'])) {
320                         return self::getCurrentApplication()['name'];
321                 } else {
322                         return 'API';
323                 }
324         }
325 }