]> git.mxchange.org Git - friendica.git/blob - src/Factory/Api/Mastodon/Status.php
Fix type and name on Mail::send sender ID argument
[friendica.git] / src / Factory / Api / Mastodon / Status.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\Factory\Api\Mastodon;
23
24 use Friendica\BaseFactory;
25 use Friendica\Content\ContactSelector;
26 use Friendica\Content\Item as ContentItem;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\Tag as TagModel;
35 use Friendica\Model\Verb;
36 use Friendica\Network\HTTPException;
37 use Friendica\Object\Api\Mastodon\Status\FriendicaDeliveryData;
38 use Friendica\Object\Api\Mastodon\Status\FriendicaExtension;
39 use Friendica\Object\Api\Mastodon\Status\FriendicaVisibility;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use ImagickException;
43 use Psr\Log\LoggerInterface;
44
45 class Status extends BaseFactory
46 {
47         /** @var Database */
48         private $dba;
49         /** @var Account */
50         private $mstdnAccountFactory;
51         /** @var Mention */
52         private $mstdnMentionFactory;
53         /** @var Tag */
54         private $mstdnTagFactory;
55         /** @var Card */
56         private $mstdnCardFactory;
57         /** @var Attachment */
58         private $mstdnAttachementFactory;
59         /** @var Error */
60         private $mstdnErrorFactory;
61         /** @var Poll */
62         private $mstdnPollFactory;
63         /** @var ContentItem */
64         private $contentItem;
65
66         public function __construct(
67                 LoggerInterface $logger,
68                 Database $dba,
69                 Account $mstdnAccountFactory,
70                 Mention $mstdnMentionFactory,
71                 Tag $mstdnTagFactory,
72                 Card $mstdnCardFactory,
73                 Attachment $mstdnAttachementFactory,
74                 Error $mstdnErrorFactory,
75                 Poll $mstdnPollFactory,
76                 ContentItem $contentItem
77         ) {
78                 parent::__construct($logger);
79                 $this->dba                     = $dba;
80                 $this->mstdnAccountFactory     = $mstdnAccountFactory;
81                 $this->mstdnMentionFactory     = $mstdnMentionFactory;
82                 $this->mstdnTagFactory         = $mstdnTagFactory;
83                 $this->mstdnCardFactory        = $mstdnCardFactory;
84                 $this->mstdnAttachementFactory = $mstdnAttachementFactory;
85                 $this->mstdnErrorFactory       = $mstdnErrorFactory;
86                 $this->mstdnPollFactory        = $mstdnPollFactory;
87                 $this->contentItem             = $contentItem;
88         }
89
90         /**
91          * @param int  $uriId           Uri-ID of the item
92          * @param int  $uid             Item user
93          * @param bool $display_quote   Display quoted posts
94          * @param bool $reblog          Check for reblogged post
95          * @param bool $in_reply_status Add an "in_reply_status" element
96          *
97          * @return \Friendica\Object\Api\Mastodon\Status
98          * @throws HTTPException\InternalServerErrorException
99          * @throws ImagickException|HTTPException\NotFoundException
100          */
101         public function createFromUriId(int $uriId, int $uid = 0, bool $display_quote = false, bool $reblog = true, bool $in_reply_status = true): \Friendica\Object\Api\Mastodon\Status
102         {
103                 $fields = ['uri-id', 'uid', 'author-id', 'causer-id', 'author-uri-id', 'author-link', 'causer-uri-id', 'post-reason', 'starred', 'app', 'title', 'body', 'raw-body', 'content-warning', 'question-id',
104                         'created', 'edited', 'commented', 'received', 'changed', 'network', 'thr-parent-id', 'parent-author-id', 'language', 'uri', 'plink', 'private', 'vid', 'gravity', 'featured', 'has-media', 'quote-uri-id',
105                         'delivery_queue_count', 'delivery_queue_done','delivery_queue_failed', 'allow_cid', 'deny_cid', 'allow_gid', 'deny_gid'];
106                 $item = Post::selectFirst($fields, ['uri-id' => $uriId, 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
107                 if (!$item) {
108                         $mail = DBA::selectFirst('mail', ['id'], ['uri-id' => $uriId, 'uid' => $uid]);
109                         if ($mail) {
110                                 return $this->createFromMailId($mail['id']);
111                         }
112                         throw new HTTPException\NotFoundException('Item with URI ID ' . $uriId . ' not found' . ($uid ? ' for user ' . $uid : '.'));
113                 }
114
115                 $activity_fields = ['uri-id', 'thr-parent-id', 'uri', 'author-id', 'author-uri-id', 'author-link', 'app', 'created', 'network', 'parent-author-id', 'private'];
116
117                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($item['vid'] == Verb::getID(Activity::ANNOUNCE))) {
118                         $is_reshare = true;
119                         $account    = $this->mstdnAccountFactory->createFromUriId($item['author-uri-id'], $uid);
120                         $uriId      = $item['thr-parent-id'];
121                         $activity   = $item;
122                         $item       = Post::selectFirst($fields, ['uri-id' => $uriId, 'uid' => [0, $uid]], ['order' => ['uid' => true]]);
123                         if (!$item) {
124                                 throw new HTTPException\NotFoundException('Item with URI ID ' . $uriId . ' not found' . ($uid ? ' for user ' . $uid : '.'));
125                         }
126                         foreach ($activity_fields as $field) {
127                                 $item[$field] = $activity[$field];
128                         }
129                 } else {
130                         $is_reshare = $reblog && !is_null($item['causer-uri-id']) && ($item['causer-id'] != $item['author-id']) && ($item['post-reason'] == Item::PR_ANNOUNCEMENT);
131                         $account    = $this->mstdnAccountFactory->createFromUriId($is_reshare ? $item['causer-uri-id'] : $item['author-uri-id'], $uid);
132                         if ($is_reshare) {
133                                 $activity = Post::selectFirstPost($activity_fields, ['thr-parent-id' => $item['uri-id'], 'author-id' => $item['causer-id'], 'verb' => Activity::ANNOUNCE]);
134                                 if ($activity) {
135                                         $item = array_merge($item, $activity);
136                                 }
137                         }
138                 }
139
140                 $count_announce = Post::countPosts([
141                         'thr-parent-id' => $uriId,
142                         'gravity'       => Item::GRAVITY_ACTIVITY,
143                         'vid'           => Verb::getID(Activity::ANNOUNCE),
144                         'deleted'       => false
145                 ]) + Post::countPosts([
146                         'quote-uri-id' => $uriId,
147                         'body'         => '',
148                         'deleted'      => false
149                 ]);
150
151                 $count_like = Post::countPosts([
152                         'thr-parent-id' => $uriId,
153                         'gravity'       => Item::GRAVITY_ACTIVITY,
154                         'vid'           => Verb::getID(Activity::LIKE),
155                         'deleted'       => false
156                 ]);
157
158                 $count_dislike = Post::countPosts([
159                         'thr-parent-id' => $uriId,
160                         'gravity'       => Item::GRAVITY_ACTIVITY,
161                         'vid'           => Verb::getID(Activity::DISLIKE),
162                         'deleted'       => false
163                 ]);
164
165                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts(
166                         Post::countPosts(['thr-parent-id' => $uriId, 'gravity' => Item::GRAVITY_COMMENT, 'deleted' => false], []),
167                         $count_announce,
168                         $count_like,
169                         $count_dislike
170                 );
171
172                 $origin_like = ($count_like == 0) ? false : Post::exists([
173                         'thr-parent-id' => $uriId,
174                         'uid'           => $uid,
175                         'origin'        => true,
176                         'gravity'       => Item::GRAVITY_ACTIVITY,
177                         'vid'           => Verb::getID(Activity::LIKE),
178                         'deleted'     => false
179                 ]);
180                 $origin_announce = ($count_announce == 0) ? false : Post::exists([
181                         'thr-parent-id' => $uriId,
182                         'uid'           => $uid,
183                         'origin'        => true,
184                         'gravity'       => Item::GRAVITY_ACTIVITY,
185                         'vid'           => Verb::getID(Activity::ANNOUNCE),
186                         'deleted'       => false
187                 ]) || Post::exists([
188                         'quote-uri-id' => $uriId,
189                         'uid'           => $uid,
190                         'origin'        => true,
191                         'body'          => '',
192                         'deleted'       => false
193                 ]);
194                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(
195                         $origin_like,
196                         $origin_announce,
197                         Post\ThreadUser::getIgnored($uriId, $uid),
198                         (bool)($item['starred'] && ($item['gravity'] == Item::GRAVITY_PARENT)),
199                         $item['featured']
200                 );
201
202                 $sensitive   = $this->dba->exists('tag-view', ['uri-id' => $uriId, 'name' => 'nsfw', 'type' => TagModel::HASHTAG]);
203                 $application = new \Friendica\Object\Api\Mastodon\Application($item['app'] ?: ContactSelector::networkToName($item['network'], $item['author-link']));
204
205                 $mentions    = $this->mstdnMentionFactory->createFromUriId($uriId)->getArrayCopy();
206                 $tags        = $this->mstdnTagFactory->createFromUriId($uriId);
207                 if ($item['has-media']) {
208                         $card        = $this->mstdnCardFactory->createFromUriId($uriId);
209                         $attachments = $this->mstdnAttachementFactory->createFromUriId($uriId);
210                 } else {
211                         $card        = new \Friendica\Object\Api\Mastodon\Card([]);
212                         $attachments = [];
213                 }
214
215                 if (!empty($item['question-id'])) {
216                         $poll = $this->mstdnPollFactory->createFromId($item['question-id'], $uid)->toArray();
217                 } else {
218                         $poll = null;
219                 }
220
221                 if ($display_quote) {
222                         $quote = self::createQuote($item, $uid);
223
224                         $item['body'] = BBCode::removeSharedData($item['body']);
225
226                         if (!is_null($item['raw-body'])) {
227                                 $item['raw-body'] = BBCode::removeSharedData($item['raw-body']);
228                         }
229                 } else {
230                         // We can always safely add attached activities. Real quotes are added to the body via "addSharedPost".
231                         if (empty($item['quote-uri-id'])) {
232                                 $quote = self::createQuote($item, $uid);
233                         } else {
234                                 $quote = [];
235                         }
236
237                         $shared = $this->contentItem->getSharedPost($item, ['uri-id']);
238                         if (!empty($shared)) {
239                                 $shared_uri_id = $shared['post']['uri-id'];
240
241                                 foreach ($this->mstdnMentionFactory->createFromUriId($shared_uri_id)->getArrayCopy() as $mention) {
242                                         if (!in_array($mention, $mentions)) {
243                                                 $mentions[] = $mention;
244                                         }
245                                 }
246
247                                 foreach ($this->mstdnTagFactory->createFromUriId($shared_uri_id) as $tag) {
248                                         if (!in_array($tag, $tags)) {
249                                                 $tags[] = $tag;
250                                         }
251                                 }
252
253                                 foreach ($this->mstdnAttachementFactory->createFromUriId($shared_uri_id) as $attachment) {
254                                         if (!in_array($attachment, $attachments)) {
255                                                 $attachments[] = $attachment;
256                                         }
257                                 }
258
259                                 if (empty($card->toArray())) {
260                                         $card = $this->mstdnCardFactory->createFromUriId($shared_uri_id);
261                                 }
262                         }
263
264                         if (!is_null($item['raw-body'])) {
265                                 $item['raw-body'] = $this->contentItem->addSharedPost($item, $item['raw-body']);
266                                 $item['raw-body'] = Post\Media::addHTMLLinkToBody($uriId, $item['raw-body']);
267                         } else {
268                                 $item['body'] = $this->contentItem->addSharedPost($item);
269                                 $item['body'] = Post\Media::addHTMLLinkToBody($uriId, $item['body']);
270                         }
271                 }
272
273                 if ($is_reshare) {
274                         try {
275                                 $reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray();
276                         } catch (\Exception $exception) {
277                                 Logger::info('Reshare not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
278                                 $reshare = [];
279                         }
280                 } else {
281                         $reshare = [];
282                 }
283
284                 if ($in_reply_status && ($item['gravity'] == Item::GRAVITY_COMMENT)) {
285                         try {
286                                 $in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray();
287                         } catch (\Exception $exception) {
288                                 Logger::info('Reply post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
289                                 $in_reply = [];
290                         }
291                 } else {
292                         $in_reply = [];
293                 }
294
295                 $aclFormatter = DI::aclFormatter();
296                 $delivery_data   = $uid != $item['uid'] ? null : new FriendicaDeliveryData($item['delivery_queue_count'], $item['delivery_queue_done'], $item['delivery_queue_failed']);
297                 $visibility_data = $uid != $item['uid'] ? null : new FriendicaVisibility($aclFormatter->expand($item['allow_cid']), $aclFormatter->expand($item['deny_cid']), $aclFormatter->expand($item['allow_gid']), $aclFormatter->expand($item['deny_gid']));
298                 $friendica       = new FriendicaExtension($item['title'], $item['changed'], $item['commented'], $item['received'], $counts->dislikes, $delivery_data, $visibility_data);
299
300                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $friendica, $quote, $poll);
301         }
302
303         /**
304          * Create a quote status object
305          *
306          * @param array $item
307          * @param integer $uid
308          * @return array
309          */
310         private function createQuote(array $item, int $uid): array
311         {
312                 if (empty($item['quote-uri-id'])) {
313                         $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]);
314                         if (!empty($media) && $shared_item = Post::selectFirst(['uri-id'], ['plink' => $media[0]['url'], 'uid' => [$uid, 0]])) {
315                                 $quote_id = $shared_item['uri-id'];
316                         }
317                 } else {
318                         $quote_id = $item['quote-uri-id'];
319                 }
320
321                 if (!empty($quote_id)) {
322                         try {
323                                 $quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray();
324                         } catch (\Exception $exception) {
325                                 Logger::info('Quote not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
326                                 $quote = [];
327                         }
328                 } else {
329                         $quote = [];
330                 }
331                 return $quote;
332         }
333
334         /**
335          * @param int $uriId id of the mail
336          *
337          * @return \Friendica\Object\Api\Mastodon\Status
338          * @throws HTTPException\InternalServerErrorException
339          * @throws ImagickException|HTTPException\NotFoundException
340          */
341         public function createFromMailId(int $id): \Friendica\Object\Api\Mastodon\Status
342         {
343                 $item = ActivityPub\Transmitter::getItemArrayFromMail($id, true);
344                 if (empty($item)) {
345                         $this->mstdnErrorFactory->RecordNotFound();
346                 }
347
348                 $account = $this->mstdnAccountFactory->createFromContactId($item['author-id']);
349
350                 $replies = $this->dba->count('mail', ['thr-parent-id' => $item['uri-id'], 'reply' => true]);
351
352                 $counts = new \Friendica\Object\Api\Mastodon\Status\Counts($replies, 0, 0, 0);
353
354                 $userAttributes = new \Friendica\Object\Api\Mastodon\Status\UserAttributes(false, false, false, false, false);
355
356                 $sensitive   = false;
357                 $application = new \Friendica\Object\Api\Mastodon\Application('');
358                 $mentions    = [];
359                 $tags        = [];
360                 $card        = new \Friendica\Object\Api\Mastodon\Card([]);
361                 $attachments = [];
362                 $in_reply    = [];
363                 $reshare     = [];
364                 $friendica   = new FriendicaExtension('', null, null, null, 0, null, null);
365
366                 return new \Friendica\Object\Api\Mastodon\Status($item, $account, $counts, $userAttributes, $sensitive, $application, $mentions, $tags, $card, $attachments, $in_reply, $reshare, $friendica);
367         }
368 }