3 * @copyright Copyright (C) 2010-2023, 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\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;
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;
43 * @see https://docs.joinmastodon.org/methods/statuses/
45 class Statuses extends BaseApi
47 public function put(array $request = [])
49 self::checkAllowedScope(self::SCOPE_WRITE);
50 $uid = self::getCurrentUserID();
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.
59 $owner = User::getOwnerDataById($uid);
63 'uri-id' => $this->parameters['id'],
64 'contact-id' => $owner['id'],
65 'author-id' => Contact::getPublicIdByUserId($uid),
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 . '.');
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' => ''];
77 if (!empty($request['language'])) {
78 $item['language'] = json_encode([$request['language'] => 1]);
81 if ($post['gravity'] == 0) {
82 $item['title'] = $request['friendica']['title'] ?? '';
85 $spoiler_text = $request['spoiler_text'];
87 if (!empty($spoiler_text)) {
88 if (!isset($request['friendica']['title']) && $post['gravity'] == 0 && DI::pConfig()->get($uid, 'system', 'api_spoiler_title', true)) {
89 $item['title'] = $spoiler_text;
91 $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $spoiler_text . "[/abstract]\n" . $item['body'];
92 $item['content-warning'] = BBCode::toPlaintext($spoiler_text);
96 if (!Item::isValid($item)) {
97 throw new \Exception('Missing parameters in definitien');
100 Item::update($item, ['id' => $post['id']]);
101 Item::updateDisplayCache($post['uri-id']);
103 System::jsonExit(DI::mstdnStatus()->createFromUriId($post['uri-id'], $uid, self::appSupportsQuotes()));
106 protected function post(array $request = [])
108 self::checkAllowedScope(self::SCOPE_WRITE);
109 $uid = self::getCurrentUserID();
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
125 $owner = User::getOwnerDataById($uid);
127 // The imput is defined as text. So we can use Markdown for some enhancements
128 $body = Markdown::toBBCode($request['status']);
131 $item['network'] = Protocol::DFRN;
133 $item['verb'] = Activity::POST;
134 $item['contact-id'] = $owner['id'];
135 $item['author-id'] = $item['owner-id'] = Contact::getPublicIdByUserId($uid);
137 $item['body'] = $body;
138 $item['app'] = $this->getApp();
140 switch ($request['visibility']) {
142 $item['allow_cid'] = '';
143 $item['allow_gid'] = '';
144 $item['deny_cid'] = '';
145 $item['deny_gid'] = '';
146 $item['private'] = Item::PUBLIC;
149 $item['allow_cid'] = '';
150 $item['allow_gid'] = '';
151 $item['deny_cid'] = '';
152 $item['deny_gid'] = '';
153 $item['private'] = Item::UNLISTED;
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'];
162 $item['allow_cid'] = '';
163 $item['allow_gid'] = '<' . Group::FOLLOWERS . '>';
164 $item['deny_cid'] = '';
165 $item['deny_gid'] = '';
167 $item['private'] = Item::PRIVATE;
170 $item['private'] = Item::PRIVATE;
171 // The permissions are assigned in "expandTags"
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'] = '';
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'];
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;
191 $item['private'] = Item::PUBLIC;
196 if (!empty($request['language'])) {
197 $item['language'] = json_encode([$request['language'] => 1]);
200 if ($request['in_reply_to_id']) {
201 $parent = Post::selectFirst(['uri', 'private'], ['uri-id' => $request['in_reply_to_id'], 'uid' => [0, $uid]]);
203 $item['thr-parent'] = $parent['uri'];
204 $item['gravity'] = Item::GRAVITY_COMMENT;
205 $item['object-type'] = Activity\ObjectType::COMMENT;
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.');
211 self::checkThrottleLimit();
213 $item['gravity'] = Item::GRAVITY_PARENT;
214 $item['object-type'] = Activity\ObjectType::NOTE;
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 . '.');
221 $item['quote-uri-id'] = $request['quote_id'];
224 $item['title'] = $request['friendica']['title'] ?? '';
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'];
230 $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $request['spoiler_text'] . "[/abstract]\n" . $item['body'];
234 $item = DI::contentItem()->expandTags($item, $request['visibility'] == 'direct');
236 if (!empty($request['media_ids'])) {
237 $item['object-type'] = Activity\ObjectType::IMAGE;
238 $item['post-type'] = Item::PT_IMAGE;
239 $item['attachments'] = [];
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));
250 Photo::setPermissionForRessource($media[0]['resource-id'], $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
252 $ressources[] = $media[0]['resource-id'];
253 $phototypes = Images::supportedTypes();
254 $ext = $phototypes[$media[0]['type']];
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']];
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'];
269 $item['attachments'][] = $attachment;
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']);
278 DI::mstdnError()->InternalError();
280 System::jsonExit(DI::mstdnScheduledStatus()->createFromDelayedPostId($id, $uid)->toArray());
283 $id = Item::insert($item, true);
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()));
291 DI::mstdnError()->InternalError();
294 protected function delete(array $request = [])
296 self::checkAllowedScope(self::SCOPE_READ);
297 $uid = self::getCurrentUserID();
299 if (empty($this->parameters['id'])) {
300 DI::mstdnError()->UnprocessableEntity();
303 $item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => $uid]);
304 if (empty($item['id'])) {
305 DI::mstdnError()->RecordNotFound();
308 if (!Item::markForDeletionById($item['id'])) {
309 DI::mstdnError()->RecordNotFound();
312 System::jsonExit([]);
316 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318 protected function rawContent(array $request = [])
320 $uid = self::getCurrentUserID();
322 if (empty($this->parameters['id'])) {
323 DI::mstdnError()->UnprocessableEntity();
326 System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid, self::appSupportsQuotes(), false));
329 private function getApp(): string
331 if (!empty(self::getCurrentApplication()['name'])) {
332 return self::getCurrentApplication()['name'];