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