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\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;
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;
45 * @see https://docs.joinmastodon.org/methods/statuses/
47 class Statuses extends BaseApi
49 public function put(array $request = [])
51 self::checkAllowedScope(self::SCOPE_WRITE);
52 $uid = self::getCurrentUserID();
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.
61 $owner = User::getOwnerDataById($uid);
65 'uri-id' => $this->parameters['id'],
66 'contact-id' => $owner['id'],
67 'author-id' => Contact::getPublicIdByUserId($uid),
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 . '.');
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' => ''];
79 if (!empty($request['language'])) {
80 $item['language'] = json_encode([$request['language'] => 1]);
83 if ($post['gravity'] == Item::GRAVITY_PARENT) {
84 $item['title'] = $request['friendica']['title'] ?? '';
87 $spoiler_text = $request['spoiler_text'];
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;
93 $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $spoiler_text . "[/abstract]\n" . $item['body'];
94 $item['content-warning'] = BBCode::toPlaintext($spoiler_text);
98 if (!Item::isValid($item)) {
99 throw new \Exception('Missing parameters in definitien');
102 Item::update($item, ['id' => $post['id']]);
103 Item::updateDisplayCache($post['uri-id']);
105 System::jsonExit(DI::mstdnStatus()->createFromUriId($post['uri-id'], $uid, self::appSupportsQuotes()));
108 protected function post(array $request = [])
110 self::checkAllowedScope(self::SCOPE_WRITE);
111 $uid = self::getCurrentUserID();
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
127 $owner = User::getOwnerDataById($uid);
129 // The imput is defined as text. So we can use Markdown for some enhancements
130 $body = Markdown::toBBCode($request['status']);
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);
137 $item['network'] = Protocol::DFRN;
139 $item['verb'] = Activity::POST;
140 $item['contact-id'] = $owner['id'];
141 $item['author-id'] = $item['owner-id'] = Contact::getPublicIdByUserId($uid);
143 $item['body'] = $body;
144 $item['app'] = $this->getApp();
146 switch ($request['visibility']) {
148 $item['allow_cid'] = '';
149 $item['allow_gid'] = '';
150 $item['deny_cid'] = '';
151 $item['deny_gid'] = '';
152 $item['private'] = Item::PUBLIC;
155 $item['allow_cid'] = '';
156 $item['allow_gid'] = '';
157 $item['deny_cid'] = '';
158 $item['deny_gid'] = '';
159 $item['private'] = Item::UNLISTED;
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'];
168 $item['allow_cid'] = '';
169 $item['allow_gid'] = '<' . Group::FOLLOWERS . '>';
170 $item['deny_cid'] = '';
171 $item['deny_gid'] = '';
173 $item['private'] = Item::PRIVATE;
176 $item['private'] = Item::PRIVATE;
177 // The permissions are assigned in "expandTags"
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'] = '';
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'];
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;
197 $item['private'] = Item::PUBLIC;
202 if (!empty($request['language'])) {
203 $item['language'] = json_encode([$request['language'] => 1]);
206 if ($request['in_reply_to_id']) {
207 $parent = Post::selectFirst(['uri', 'private'], ['uri-id' => $request['in_reply_to_id'], 'uid' => [0, $uid]]);
209 $item['thr-parent'] = $parent['uri'];
210 $item['gravity'] = Item::GRAVITY_COMMENT;
211 $item['object-type'] = Activity\ObjectType::COMMENT;
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.');
217 self::checkThrottleLimit();
219 $item['gravity'] = Item::GRAVITY_PARENT;
220 $item['object-type'] = Activity\ObjectType::NOTE;
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 . '.');
227 $item['quote-uri-id'] = $request['quote_id'];
230 $item['title'] = $request['friendica']['title'] ?? '';
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'];
236 $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $request['spoiler_text'] . "[/abstract]\n" . $item['body'];
240 $item = DI::contentItem()->expandTags($item, $request['visibility'] == 'direct');
242 if (!empty($request['media_ids'])) {
243 $item['object-type'] = Activity\ObjectType::IMAGE;
244 $item['post-type'] = Item::PT_IMAGE;
245 $item['attachments'] = [];
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));
256 Photo::setPermissionForRessource($media[0]['resource-id'], $uid, $item['allow_cid'], $item['allow_gid'], $item['deny_cid'], $item['deny_gid']);
258 $ressources[] = $media[0]['resource-id'];
259 $phototypes = Images::supportedTypes();
260 $ext = $phototypes[$media[0]['type']];
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']];
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'];
275 $item['attachments'][] = $attachment;
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']));
284 DI::mstdnError()->InternalError();
286 System::jsonExit(DI::mstdnScheduledStatus()->createFromDelayedPostId($id, $uid)->toArray());
289 $id = Item::insert($item, true);
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()));
297 DI::mstdnError()->InternalError();
300 protected function delete(array $request = [])
302 self::checkAllowedScope(self::SCOPE_READ);
303 $uid = self::getCurrentUserID();
305 if (empty($this->parameters['id'])) {
306 DI::mstdnError()->UnprocessableEntity();
309 $item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => $uid]);
310 if (empty($item['id'])) {
311 DI::mstdnError()->RecordNotFound();
314 if (!Item::markForDeletionById($item['id'])) {
315 DI::mstdnError()->RecordNotFound();
318 System::jsonExit([]);
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 protected function rawContent(array $request = [])
326 $uid = self::getCurrentUserID();
328 if (empty($this->parameters['id'])) {
329 DI::mstdnError()->UnprocessableEntity();
332 System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid, self::appSupportsQuotes(), false));
335 private function getApp(): string
337 if (!empty(self::getCurrentApplication()['name'])) {
338 return self::getCurrentApplication()['name'];