]> git.mxchange.org Git - friendica.git/blobdiff - src/Module/Api/Mastodon/Statuses.php
Merge pull request #12591 from MrPetovan/task/2023-licence
[friendica.git] / src / Module / Api / Mastodon / Statuses.php
index 9bbc3bf6361515446b3b649a7206a14c7be5875f..b7b3ff14c4e8876a5d20e0511348e054776d11d1 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2010-2021, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
 
 namespace Friendica\Module\Api\Mastodon;
 
-use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\Markdown;
+use Friendica\Core\Protocol;
 use Friendica\Core\System;
+use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Contact;
@@ -33,6 +34,7 @@ use Friendica\Model\Photo;
 use Friendica\Model\Post;
 use Friendica\Model\User;
 use Friendica\Module\BaseApi;
+use Friendica\Network\HTTPException;
 use Friendica\Protocol\Activity;
 use Friendica\Util\Images;
 
@@ -41,46 +43,86 @@ use Friendica\Util\Images;
  */
 class Statuses extends BaseApi
 {
-       public static function post(array $parameters = [])
+       public function put(array $request = [])
        {
-               self::login(self::SCOPE_WRITE);
+               self::checkAllowedScope(self::SCOPE_WRITE);
                $uid = self::getCurrentUserID();
 
-               $data = self::getJsonPostData();
-
-               $status         = $data['status'] ?? '';
-               $media_ids      = $data['media_ids'] ?? [];
-               $in_reply_to_id = $data['in_reply_to_id'] ?? 0;
-               $sensitive      = $data['sensitive'] ?? false; // @todo Possibly trigger "nsfw" flag?
-               $spoiler_text   = $data['spoiler_text'] ?? '';
-               $visibility     = $data['visibility'] ?? '';
-               $scheduled_at   = $data['scheduled_at'] ?? ''; // Currently unsupported, but maybe in the future
-               $language       = $data['language'] ?? '';
+               $request = $this->getRequest([
+                       'status'         => '',    // Text content of the status. If media_ids is provided, this becomes optional. Attaching a poll is optional while status is provided.
+                       'in_reply_to_id' => 0,     // ID of the status being replied to, if status is a reply
+                       'spoiler_text'   => '',    // Text to be shown as a warning or subject before the actual content. Statuses are generally collapsed behind this field.
+                       'language'       => '',    // ISO 639 language code for this status.
+               ], $request);
 
                $owner = User::getOwnerDataById($uid);
 
+               $condition = [
+                       'uid'        => $uid,
+                       'uri-id'     => $this->parameters['id'],
+                       'contact-id' => $owner['id'],
+                       'author-id'  => Contact::getPublicIdByUserId($uid),
+                       'origin'     => true,
+               ];
+
+               $post = Post::selectFirst(['uri-id', 'id'], $condition);
+               if (empty($post['id'])) {
+                       throw new HTTPException\NotFoundException('Item with URI ID ' . $this->parameters['id'] . ' not found for user ' . $uid . '.');
+               }
+
                // The imput is defined as text. So we can use Markdown for some enhancements
-               $body = Markdown::toBBCode($status);
+               $item = ['body' => Markdown::toBBCode($request['status']), 'app' => $this->getApp()];
+
+               if (!empty($request['language'])) {
+                       $item['language'] = json_encode([$request['language'] => 1]);
+               }
+
+               if (!empty($request['spoiler_text'])) {
+                       if ($request['in_reply_to_id'] != $post['uri-id']) {
+                               $item['body'] = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $request['spoiler_text'] . "[/abstract]\n" . $item['body'];
+                       } else {
+                               $item['title'] = $request['spoiler_text'];
+                       }
+               }
+
+               Item::update($item, ['id' => $post['id']]);
+               Item::updateDisplayCache($post['uri-id']);
+
+               System::jsonExit(DI::mstdnStatus()->createFromUriId($post['uri-id'], $uid));
+       }
+
+       protected function post(array $request = [])
+       {
+               self::checkAllowedScope(self::SCOPE_WRITE);
+               $uid = self::getCurrentUserID();
 
-               $body = BBCode::expandTags($body);
+               $request = $this->getRequest([
+                       'status'         => '',    // Text content of the status. If media_ids is provided, this becomes optional. Attaching a poll is optional while status is provided.
+                       'media_ids'      => [],    // Array of Attachment ids to be attached as media. If provided, status becomes optional, and poll cannot be used.
+                       'poll'           => [],    // Poll data. If provided, media_ids cannot be used, and poll[expires_in] must be provided.
+                       'in_reply_to_id' => 0,     // ID of the status being replied to, if status is a reply
+                       'sensitive'      => false, // Mark status and attached media as sensitive?
+                       'spoiler_text'   => '',    // Text to be shown as a warning or subject before the actual content. Statuses are generally collapsed behind this field.
+                       'visibility'     => '',    // Visibility of the posted status. One of: "public", "unlisted", "private" or "direct".
+                       '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.
+                       'language'       => '',    // ISO 639 language code for this status.
+               ], $request);
+
+               $owner = User::getOwnerDataById($uid);
 
-               $item = [];
+               // The imput is defined as text. So we can use Markdown for some enhancements
+               $body = Markdown::toBBCode($request['status']);
+
+               $item               = [];
+               $item['network']    = Protocol::DFRN;
                $item['uid']        = $uid;
                $item['verb']       = Activity::POST;
                $item['contact-id'] = $owner['id'];
                $item['author-id']  = $item['owner-id'] = Contact::getPublicIdByUserId($uid);
-               $item['title']      = $spoiler_text;
                $item['body']       = $body;
+               $item['app']        = $this->getApp();
 
-               if (!empty(self::getCurrentApplication()['name'])) {
-                       $item['app'] = self::getCurrentApplication()['name'];
-               }
-
-               if (empty($item['app'])) {
-                       $item['app'] = 'API';
-               }
-
-               switch ($visibility) {
+               switch ($request['visibility']) {
                        case 'public':
                                $item['allow_cid'] = '';
                                $item['allow_gid'] = '';
@@ -103,21 +145,27 @@ class Statuses extends BaseApi
                                        $item['deny_gid']  = $owner['deny_gid'];
                                } else {
                                        $item['allow_cid'] = '';
-                                       $item['allow_gid'] = [Group::FOLLOWERS];
+                                       $item['allow_gid'] = '<' . Group::FOLLOWERS . '>';
                                        $item['deny_cid']  = '';
                                        $item['deny_gid']  = '';
                                }
                                $item['private'] = Item::PRIVATE;
                                break;
                        case 'direct':
-                               // Direct messages are currently unsupported
-                               DI::mstdnError()->InternalError('Direct messages are currently unsupported');
-                               break;          
+                               // The permissions are assigned in "expandTags"
+                               break;
                        default:
-                               $item['allow_cid'] = $owner['allow_cid'];
-                               $item['allow_gid'] = $owner['allow_gid'];
-                               $item['deny_cid']  = $owner['deny_cid'];
-                               $item['deny_gid']  = $owner['deny_gid'];
+                               if (is_numeric($request['visibility']) && Group::exists($request['visibility'], $uid)) {
+                                       $item['allow_cid'] = '';
+                                       $item['allow_gid'] = '<' . $request['visibility'] . '>';
+                                       $item['deny_cid']  = '';
+                                       $item['deny_gid']  = '';
+                               } else {
+                                       $item['allow_cid'] = $owner['allow_cid'];
+                                       $item['allow_gid'] = $owner['allow_gid'];
+                                       $item['deny_cid']  = $owner['deny_cid'];
+                                       $item['deny_gid']  = $owner['deny_gid'];
+                               }
 
                                if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
                                        $item['private'] = Item::PRIVATE;
@@ -129,30 +177,37 @@ class Statuses extends BaseApi
                                break;
                }
 
-               if (!empty($language)) {
-                       $item['language'] = json_encode([$language => 1]);
+               if (!empty($request['language'])) {
+                       $item['language'] = json_encode([$request['language'] => 1]);
                }
 
-               if ($in_reply_to_id) {
-                       $parent = Post::selectFirst(['uri'], ['uri-id' => $in_reply_to_id, 'uid' => [0, $uid]]);
+               if ($request['in_reply_to_id']) {
+                       $parent = Post::selectFirst(['uri'], ['uri-id' => $request['in_reply_to_id'], 'uid' => [0, $uid]]);
+
                        $item['thr-parent']  = $parent['uri'];
-                       $item['gravity']     = GRAVITY_COMMENT;
+                       $item['gravity']     = Item::GRAVITY_COMMENT;
                        $item['object-type'] = Activity\ObjectType::COMMENT;
+                       $item['body']        = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $request['spoiler_text'] . "[/abstract]\n" . $item['body'];
                } else {
-                       $item['gravity']     = GRAVITY_PARENT;
+                       self::checkThrottleLimit();
+
+                       $item['gravity']     = Item::GRAVITY_PARENT;
                        $item['object-type'] = Activity\ObjectType::NOTE;
+                       $item['title']       = $request['spoiler_text'];
                }
 
-               if (!empty($media_ids)) {
+               $item = DI::contentItem()->expandTags($item, $request['visibility'] == 'direct');
+
+               if (!empty($request['media_ids'])) {
                        $item['object-type'] = Activity\ObjectType::IMAGE;
                        $item['post-type']   = Item::PT_IMAGE;
                        $item['attachments'] = [];
 
-                       foreach ($media_ids as $id) {
+                       foreach ($request['media_ids'] as $id) {
                                $media = DBA::toArray(DBA::p("SELECT `resource-id`, `scale`, `type`, `desc`, `filename`, `datasize`, `width`, `height` FROM `photo`
                                                WHERE `resource-id` IN (SELECT `resource-id` FROM `photo` WHERE `id` = ?) AND `photo`.`uid` = ?
                                                ORDER BY `photo`.`width` DESC LIMIT 2", $id, $uid));
-                                       
+
                                if (empty($media)) {
                                        continue;
                                }
@@ -162,7 +217,7 @@ class Statuses extends BaseApi
                                $ressources[] = $media[0]['resource-id'];
                                $phototypes = Images::supportedTypes();
                                $ext = $phototypes[$media[0]['type']];
-                       
+
                                $attachment = ['type' => Post\Media::IMAGE, 'mimetype' => $media[0]['type'],
                                        'url' => DI::baseUrl() . '/photo/' . $media[0]['resource-id'] . '-' . $media[0]['scale'] . '.' . $ext,
                                        'size' => $media[0]['datasize'],
@@ -170,7 +225,7 @@ class Statuses extends BaseApi
                                        'description' => $media[0]['desc'] ?? '',
                                        'width' => $media[0]['width'],
                                        'height' => $media[0]['height']];
-                       
+
                                if (count($media) > 1) {
                                        $attachment['preview'] = DI::baseUrl() . '/photo/' . $media[1]['resource-id'] . '-' . $media[1]['scale'] . '.' . $ext;
                                        $attachment['preview-width'] = $media[1]['width'];
@@ -180,27 +235,37 @@ class Statuses extends BaseApi
                        }
                }
 
+               if (!empty($request['scheduled_at'])) {
+                       $item['guid'] = Item::guid($item, true);
+                       $item['uri'] = Item::newURI($item['guid']);
+                       $id = Post\Delayed::add($item['uri'], $item, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED, $request['scheduled_at']);
+                       if (empty($id)) {
+                               DI::mstdnError()->InternalError();
+                       }
+                       System::jsonExit(DI::mstdnScheduledStatus()->createFromDelayedPostId($id, $uid)->toArray());
+               }
+
                $id = Item::insert($item, true);
                if (!empty($id)) {
                        $item = Post::selectFirst(['uri-id'], ['id' => $id]);
                        if (!empty($item['uri-id'])) {
-                               System::jsonExit(DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid));            
+                               System::jsonExit(DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid));
                        }
                }
 
                DI::mstdnError()->InternalError();
        }
 
-       public static function delete(array $parameters = [])
+       protected function delete(array $request = [])
        {
-               self::login(self::SCOPE_READ);
+               self::checkAllowedScope(self::SCOPE_READ);
                $uid = self::getCurrentUserID();
 
-               if (empty($parameters['id'])) {
+               if (empty($this->parameters['id'])) {
                        DI::mstdnError()->UnprocessableEntity();
                }
 
-               $item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $parameters['id'], 'uid' => $uid]);
+               $item = Post::selectFirstForUser($uid, ['id'], ['uri-id' => $this->parameters['id'], 'uid' => $uid]);
                if (empty($item['id'])) {
                        DI::mstdnError()->RecordNotFound();
                }
@@ -213,15 +278,25 @@ class Statuses extends BaseApi
        }
 
        /**
-        * @param array $parameters
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       public static function rawContent(array $parameters = [])
+       protected function rawContent(array $request = [])
        {
-               if (empty($parameters['id'])) {
+               $uid = self::getCurrentUserID();
+
+               if (empty($this->parameters['id'])) {
                        DI::mstdnError()->UnprocessableEntity();
                }
 
-               System::jsonExit(DI::mstdnStatus()->createFromUriId($parameters['id'], self::getCurrentUserID()));
+               System::jsonExit(DI::mstdnStatus()->createFromUriId($this->parameters['id'], $uid));
+       }
+
+       private function getApp(): string
+       {
+               if (!empty(self::getCurrentApplication()['name'])) {
+                       return self::getCurrentApplication()['name'];
+               } else {
+                       return 'API';
+               }
        }
 }