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