]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
Merge pull request #13646 from annando/page-drop
[friendica.git] / src / Content / Item.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\Content;
23
24 use Friendica\App;
25 use Friendica\App\BaseURL;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\BBCode\Video;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Hook;
30 use Friendica\Core\L10n;
31 use Friendica\Core\Logger;
32 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
33 use Friendica\Core\Protocol;
34 use Friendica\Core\Session\Capability\IHandleUserSessions;
35 use Friendica\Core\System;
36 use Friendica\Database\DBA;
37 use Friendica\DI;
38 use Friendica\Model\Attach;
39 use Friendica\Model\Circle;
40 use Friendica\Model\Contact;
41 use Friendica\Model\Conversation;
42 use Friendica\Model\FileTag;
43 use Friendica\Model\Item as ItemModel;
44 use Friendica\Model\Photo;
45 use Friendica\Model\Post;
46 use Friendica\Model\Tag;
47 use Friendica\Model\User;
48 use Friendica\Network\HTTPException;
49 use Friendica\Object\EMail\ItemCCEMail;
50 use Friendica\Protocol\Activity;
51 use Friendica\Protocol\ActivityPub;
52 use Friendica\Util\ACLFormatter;
53 use Friendica\Util\DateTimeFormat;
54 use Friendica\Util\Emailer;
55 use Friendica\Util\ParseUrl;
56 use Friendica\Util\Profiler;
57 use Friendica\Util\Proxy;
58 use Friendica\Util\XML;
59 use GuzzleHttp\Psr7\Uri;
60
61 /**
62  * A content helper class for displaying items
63  */
64 class Item
65 {
66         /** @var Activity */
67         private $activity;
68         /** @var L10n */
69         private $l10n;
70         /** @var Profiler */
71         private $profiler;
72         /** @var IHandleUserSessions */
73         private $userSession;
74         /** @var Video */
75         private $bbCodeVideo;
76         /** @var ACLFormatter */
77         private $aclFormatter;
78         /** @var IManagePersonalConfigValues */
79         private $pConfig;
80         /** @var BaseURL */
81         private $baseURL;
82         /** @var Emailer */
83         private $emailer;
84         /** @var App */
85         private $app;
86
87         public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession, Video $bbCodeVideo, ACLFormatter $aclFormatter, IManagePersonalConfigValues $pConfig, BaseURL $baseURL, Emailer $emailer, App $app)
88         {
89                 $this->profiler     = $profiler;
90                 $this->activity     = $activity;
91                 $this->l10n         = $l10n;
92                 $this->userSession  = $userSession;
93                 $this->bbCodeVideo  = $bbCodeVideo;
94                 $this->aclFormatter = $aclFormatter;
95                 $this->baseURL      = $baseURL;
96                 $this->pConfig      = $pConfig;
97                 $this->emailer      = $emailer;
98                 $this->app          = $app;
99         }
100
101         /**
102          * Lists categories and folders for an item
103          *
104          * @param array $item
105          * @param int   $uid
106          * @return array
107          * [
108          *     [ // categories array
109          *         {
110          *             'name': 'category name',
111          *             'removeurl': 'url to remove this category',
112          *             'first': 'is the first in this array? true/false',
113          *             'last': 'is the last in this array? true/false',
114          *         },
115          *         ...
116          *     ],
117          *     [ //folders array
118          *         {
119          *             'name': 'folder name',
120          *             'removeurl': 'url to remove this folder',
121          *             'first': 'is the first in this array? true/false',
122          *             'last': 'is the last in this array? true/false',
123          *         } ,
124          *         ...
125          *     ]
126          * ]
127          *
128          * @throws \Exception
129          */
130         public function determineCategoriesTerms(array $item, int $uid = 0): array
131         {
132                 $categories = [];
133                 $folders = [];
134                 $first = true;
135
136                 $uid = $item['uid'] ?: $uid;
137
138                 if (empty($item['has-categories'])) {
139                         return [$categories, $folders];
140                 }
141
142                 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid) as $savedFolderName) {
143                         if (!empty($item['author-link'])) {
144                                 $url = $item['author-link'] . '/conversations?category=' . rawurlencode($savedFolderName);
145                         } else {
146                                 $url = '#';
147                         }
148                         $categories[] = [
149                                 'name' => $savedFolderName,
150                                 'url' => $url,
151                                 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
152                                 'first' => $first,
153                                 'last' => false
154                         ];
155                         $first = false;
156                 }
157
158                 if (count($categories)) {
159                         $categories[count($categories) - 1]['last'] = true;
160                 }
161
162                 if ($this->userSession->getLocalUserId() == $uid) {
163                         foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
164                                 $folders[] = [
165                                         'name' => $savedFolderName,
166                                         'url' => "#",
167                                         'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
168                                         'first' => $first,
169                                         'last' => false
170                                 ];
171                                 $first = false;
172                         }
173                 }
174
175                 if (count($folders)) {
176                         $folders[count($folders) - 1]['last'] = true;
177                 }
178
179                 return [$categories, $folders];
180         }
181
182         /**
183          * This function removes the tag $tag from the text $body and replaces it with
184          * the appropriate link.
185          *
186          * @param string $body        the text to replace the tag in
187          * @param int    $profile_uid the user id to replace the tag for (0 = anyone)
188          * @param string $tag         the tag to replace
189          * @param string $network     The network of the post
190          *
191          * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
192          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193          * @throws \ImagickException
194          */
195         public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
196         {
197                 $replaced = false;
198
199                 //is it a person tag?
200                 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
201                         $tag_type = substr($tag, 0, 1);
202                         //is it already replaced?
203                         if (strpos($tag, '[url=')) {
204                                 return $replaced;
205                         }
206
207                         //get the person's name
208                         $name = substr($tag, 1);
209
210                         // Sometimes the tag detection doesn't seem to work right
211                         // This is some workaround
212                         $nameparts = explode(' ', $name);
213                         $name = $nameparts[0];
214
215                         // Try to detect the contact in various ways
216                         if (strpos($name, 'http://') || strpos($name, '@')) {
217                                 $contact = Contact::getByURLForUser($name, $profile_uid);
218                         } else {
219                                 $contact = false;
220                                 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
221
222                                 if (strrpos($name, '+')) {
223                                         // Is it in format @nick+number?
224                                         $tagcid = intval(substr($name, strrpos($name, '+') + 1));
225                                         $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
226                                 }
227
228                                 // select someone by nick in the current network
229                                 if (!DBA::isResult($contact) && ($network != '')) {
230                                         $condition = ['nick' => $name, 'network' => $network, 'uid' => $profile_uid];
231                                         $contact = DBA::selectFirst('contact', $fields, $condition);
232                                 }
233
234                                 // select someone by attag in the current network
235                                 if (!DBA::isResult($contact) && ($network != '')) {
236                                         $condition = ['attag' => $name, 'network' => $network, 'uid' => $profile_uid];
237                                         $contact = DBA::selectFirst('contact', $fields, $condition);
238                                 }
239
240                                 //select someone by name in the current network
241                                 if (!DBA::isResult($contact) && ($network != '')) {
242                                         $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
243                                         $contact = DBA::selectFirst('contact', $fields, $condition);
244                                 }
245
246                                 // select someone by nick in any network
247                                 if (!DBA::isResult($contact)) {
248                                         $condition = ['nick' => $name, 'uid' => $profile_uid];
249                                         $contact = DBA::selectFirst('contact', $fields, $condition);
250                                 }
251
252                                 // select someone by attag in any network
253                                 if (!DBA::isResult($contact)) {
254                                         $condition = ['attag' => $name, 'uid' => $profile_uid];
255                                         $contact = DBA::selectFirst('contact', $fields, $condition);
256                                 }
257
258                                 // select someone by name in any network
259                                 if (!DBA::isResult($contact)) {
260                                         $condition = ['name' => $name, 'uid' => $profile_uid];
261                                         $contact = DBA::selectFirst('contact', $fields, $condition);
262                                 }
263                         }
264
265                         // Check if $contact has been successfully loaded
266                         if (DBA::isResult($contact)) {
267                                 $profile = $contact['url'];
268                                 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
269                         }
270
271                         //if there is an url for this persons profile
272                         if (isset($profile) && ($newname != '')) {
273                                 $replaced = true;
274                                 // create profile link
275                                 $profile = str_replace(',', '%2c', $profile);
276                                 $newtag = $tag_type . '[url=' . $profile . ']' . $newname . '[/url]';
277                                 $body = str_replace($tag_type . $name, $newtag, $body);
278                         }
279                 }
280
281                 return ['replaced' => $replaced, 'contact' => $contact];
282         }
283
284         /**
285          * Render actions localized
286          *
287          * @param array $item
288          * @return void
289          * @throws ImagickException
290          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291          */
292         public function localize(array &$item)
293         {
294                 $this->profiler->startRecording('rendering');
295                 /// @todo The following functionality needs to be cleaned up.
296                 if (!empty($item['verb'])) {
297                         $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
298
299                         if ($this->activity->match($item['verb'], Activity::TAG)) {
300                                 $fields = [
301                                         'author-id', 'author-link', 'author-name', 'author-network', 'author-link', 'author-alias',
302                                         'verb', 'object-type', 'resource-id', 'body', 'plink'
303                                 ];
304                                 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
305                                 if (!DBA::isResult($obj)) {
306                                         $this->profiler->stopRecording();
307                                         return;
308                                 }
309
310                                 $author_arr = [
311                                         'uid'     => 0,
312                                         'id'      => $item['author-id'],
313                                         'network' => $item['author-network'],
314                                         'url'     => $item['author-link'],
315                                         'alias'   => $item['author-alias'],
316                                 ];
317                                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
318
319                                 $author_arr = [
320                                         'uid'     => 0,
321                                         'id'      => $obj['author-id'],
322                                         'network' => $obj['author-network'],
323                                         'url'     => $obj['author-link'],
324                                         'alias'   => $obj['author-alias'],
325                                 ];
326                                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
327
328                                 switch ($obj['verb']) {
329                                         case Activity::POST:
330                                                 switch ($obj['object-type']) {
331                                                         case Activity\ObjectType::EVENT:
332                                                                 $post_type = $this->l10n->t('event');
333                                                                 break;
334                                                         default:
335                                                                 $post_type = $this->l10n->t('status');
336                                                 }
337                                                 break;
338
339                                         default:
340                                                 if ($obj['resource-id']) {
341                                                         $post_type = $this->l10n->t('photo');
342                                                         preg_match("/\[url=([^]]*)\]/", $obj['body'], $matches);
343                                                         $rr['plink'] = $matches[1];
344                                                 } else {
345                                                         $post_type = $this->l10n->t('status');
346                                                 }
347                                                 // Let's break everything ... ;-)
348                                                 break;
349                                 }
350                                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
351
352                                 $parsedobj = XML::parseString($xmlhead . $item['object']);
353
354                                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
355                                 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
356                         }
357                 }
358
359                 $this->profiler->stopRecording();
360         }
361
362         /**
363          * Renders photo menu based on item
364          *
365          * @param array $item
366          * @param string $formSecurityToken
367          * @return string
368          */
369         public function photoMenu(array $item, string $formSecurityToken): string
370         {
371                 $this->profiler->startRecording('rendering');
372                 $sub_link = $contact_url = $pm_url = $status_link = '';
373                 $photos_link = $posts_link = $block_link = $ignore_link = $collapse_link = $ignoreserver_link = '';
374
375                 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
376                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
377                 }
378
379                 $author = [
380                         'uid'     => 0,
381                         'id'      => $item['author-id'],
382                         'network' => $item['author-network'],
383                         'url'     => $item['author-link'],
384                         'alias'   => $item['author-alias'],
385                 ];
386                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
387                 if (strpos($profile_link, 'contact/redir/') === 0) {
388                         $status_link  = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/status']);
389                         $photos_link  = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/photos']);
390                         $profile_link = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/profile']);
391                 }
392
393                 $cid = 0;
394                 $pcid = $item['author-id'];
395                 $network = '';
396                 $rel = 0;
397                 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
398                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
399                 if (DBA::isResult($contact)) {
400                         $cid = $contact['id'];
401                         $network = $contact['network'];
402                         $rel = $contact['rel'];
403                 }
404
405                 if (!empty($pcid)) {
406                         $contact_url   = 'contact/' . $pcid;
407                         $posts_link    = $contact_url . '/posts';
408                         $block_link    = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
409                         $ignore_link   = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
410                         $collapse_link = $item['self'] ? '' : $contact_url . '/collapse?t=' . $formSecurityToken;
411                 }
412
413                 $authorBaseUri = new Uri($item['author-baseurl'] ?? '');
414                 if (!empty($item['author-gsid']) && $authorBaseUri->getHost() && !DI::baseUrl()->isLocalUrl($authorBaseUri)) {
415                         $ignoreserver_link = 'settings/server/' . $item['author-gsid'] . '/ignore';
416                 }
417
418                 if ($cid && !$item['self']) {
419                         $contact_url = 'contact/' . $cid;
420                         $posts_link  = $contact_url . '/posts';
421
422                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
423                                 $pm_url = 'message/new/' . $cid;
424                         }
425                 }
426
427                 if ($this->userSession->getLocalUserId()) {
428                         $menu = [
429                                 $this->l10n->t('Follow Thread') => $sub_link,
430                                 $this->l10n->t('View Status') => $status_link,
431                                 $this->l10n->t('View Profile') => $profile_link,
432                                 $this->l10n->t('View Photos') => $photos_link,
433                                 $this->l10n->t('Network Posts') => $posts_link,
434                                 $this->l10n->t('View Contact') => $contact_url,
435                                 $this->l10n->t('Send PM') => $pm_url,
436                                 $this->l10n->t('Block') => $block_link,
437                                 $this->l10n->t('Ignore') => $ignore_link,
438                                 $this->l10n->t('Collapse') => $collapse_link,
439                                 $this->l10n->t("Ignore %s server", $authorBaseUri->getHost()) => $ignoreserver_link,
440                         ];
441
442                         if (!empty($item['language'])) {
443                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
444                         }
445
446                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
447                                 in_array($item['network'], Protocol::FEDERATED)
448                         ) {
449                                 $menu[$this->l10n->t('Connect/Follow')] = 'contact/follow?url=' . urlencode($item['author-link']) . '&auto=1';
450                         }
451                 } else {
452                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
453                 }
454
455                 $args = ['item' => $item, 'menu' => $menu];
456
457                 Hook::callAll('item_photo_menu', $args);
458
459                 $menu = $args['menu'];
460
461                 $o = '';
462                 foreach ($menu as $k => $v) {
463                         if (strpos($v, 'javascript:') === 0) {
464                                 $v = substr($v, 11);
465                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
466                         } elseif ($v) {
467                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
468                         }
469                 }
470                 $this->profiler->stopRecording();
471                 return $o;
472         }
473
474         /**
475          * Checks if the activity is visible to current user
476          *
477          * @param array $item Activity item
478          * @return bool Whether the item is visible to the user
479          */
480         public function isVisibleActivity(array $item): bool
481         {
482                 // Empty verb or hidden?
483                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
484                         return false;
485                 }
486
487                 // Check conditions
488                 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
489                         $item['object-type'] === Activity\ObjectType::NOTE &&
490                         empty($item['self']) &&
491                         $item['uid'] == $this->userSession->getLocalUserId())
492                 );
493         }
494
495         public function expandTags(array $item, bool $setPermissions = false): array
496         {
497                 // Look for any tags and linkify them
498                 $item['inform'] = '';
499                 $private_group  = false;
500                 $private_id     = null;
501                 $only_to_group  = false;
502                 $group_contact  = [];
503                 $receivers      = [];
504
505                 // Convert mentions in the body to a unified format
506                 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
507
508                 // Search for group mentions
509                 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
510                         $contact = Contact::getByURLForUser($tag[2], $item['uid']);
511                         if (empty($contact)) {
512                                 continue;
513                         }
514
515                         $receivers[] = $contact['id'];
516
517                         if (!empty($item['inform'])) {
518                                 $item['inform'] .= ',';
519                         }
520                         $item['inform'] .= 'cid:' . $contact['id'];
521
522                         if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
523                                 continue;
524                         }
525
526                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
527                                 $private_group = $contact['prv'];
528                                 $only_to_group = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
529                                 $private_id = $contact['id'];
530                                 $group_contact = $contact;
531                                 Logger::info('Private group or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
532                         } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
533                                 $private_group = false;
534                                 $only_to_group = true;
535                                 $private_id = $contact['id'];
536                                 $group_contact = $contact;
537                                 Logger::info('Public group', ['url' => $tag[2], 'mention' => $tag[1]]);
538                         } else {
539                                 Logger::info('Post with group mention will not be converted to a group post', ['url' => $tag[2], 'mention' => $tag[1]]);
540                         }
541                 }
542                 Logger::info('Got inform', ['inform' => $item['inform']]);
543
544                 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($group_contact) && ($private_group || $only_to_group)) {
545                         // we tagged a group in a top level post. Now we change the post
546                         $item['private'] = $private_group ? ItemModel::PRIVATE : ItemModel::UNLISTED;
547
548                         if ($only_to_group) {
549                                 $cdata = Contact::getPublicAndUserContactID($group_contact['id'], $item['uid']);
550                                 if (!empty($cdata['user'])) {
551                                         $item['owner-id'] = $cdata['user'];
552                                         unset($item['owner-link']);
553                                         unset($item['owner-name']);
554                                         unset($item['owner-avatar']);
555                                 }
556
557                                 $item['postopts'] = '';
558                         }
559
560                         $item['deny_cid'] = '';
561                         $item['deny_gid'] = '';
562
563                         if ($private_group) {
564                                 $item['allow_cid'] = '<' . $private_id . '>';
565                                 $item['allow_gid'] = '<' . Circle::getIdForGroup($group_contact['id']) . '>';
566                         } else {
567                                 $item['allow_cid'] = '';
568                                 $item['allow_gid'] = '';
569                         }
570                 } elseif ($setPermissions) {
571                         if (empty($receivers)) {
572                                 // For security reasons direct posts without any receiver will be posts to yourself
573                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
574                                 $receivers[] = $self['id'];
575                         }
576
577                         $item['private']   = ItemModel::PRIVATE;
578                         $item['allow_cid'] = '';
579                         $item['allow_gid'] = '';
580                         $item['deny_cid']  = '';
581                         $item['deny_gid']  = '';
582
583                         foreach ($receivers as $receiver) {
584                                 $item['allow_cid'] .= '<' . $receiver . '>';
585                         }
586                 }
587                 return $item;
588         }
589
590         public function getAuthorAvatar(array $item): string
591         {
592                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
593                         $author_avatar  = $item['contact-id'];
594                         $author_updated = '';
595                         $author_thumb   = $item['contact-avatar'];
596                 } else {
597                         $author_avatar  = $item['author-id'];
598                         $author_updated = $item['author-updated'];
599                         $author_thumb   = $item['author-avatar'];
600                 }
601
602
603                 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
604                         $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
605                 }
606
607                 return $author_thumb;
608         }
609
610         public function getOwnerAvatar(array $item): string
611         {
612                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
613                         $owner_avatar  = $item['contact-id'];
614                         $owner_updated = '';
615                         $owner_thumb   = $item['contact-avatar'];
616                 } else {
617                         $owner_avatar   = $item['owner-id'];
618                         $owner_updated  = $item['owner-updated'];
619                         $owner_thumb    = $item['owner-avatar'];
620                 }
621
622                 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
623                         $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
624                 }
625
626                 return $owner_thumb;
627         }
628
629         /**
630          * Add a share block for the given uri-id
631          *
632          * @param array  $item
633          * @param string $body
634          * @return string
635          */
636         public function addSharedPost(array $item, string $body = ''): string
637         {
638                 if (empty($body)) {
639                         $body = $item['body'] ?? '';
640                 }
641
642                 if (empty($item['quote-uri-id']) || ($item['quote-uri-id'] == $item['uri-id'])) {
643                         return $body;
644                 }
645
646                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
647                 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
648                 if (!DBA::isResult($shared_item)) {
649                         Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
650                         return $body;
651                 }
652
653                 return trim(BBCode::removeSharedData($body) . "\n" . $this->createSharedBlockByArray($shared_item, true));
654         }
655
656         /**
657          * Add a share block for the given guid
658          *
659          * @param string $guid
660          * @param integer $uid
661          * @param bool $add_media
662          * @return string
663          */
664         private function createSharedPostByGuid(string $guid, bool $add_media): string
665         {
666                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
667                 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
668
669                 if (!DBA::isResult($shared_item)) {
670                         Logger::notice('Post does not exist.', ['guid' => $guid]);
671                         return '';
672                 }
673
674                 return $this->createSharedBlockByArray($shared_item, $add_media);
675         }
676
677         /**
678          * Add a share block for the given item array
679          *
680          * @param array $item
681          * @param bool $add_media   true = Media is added to the body
682          * @param bool $for_display true = The share block is used for display purposes, false = used for connectors, transport to other systems, ...
683          * @return string
684          */
685         public function createSharedBlockByArray(array $item, bool $add_media = false, bool $for_display = false): string
686         {
687                 if ($item['network'] == Protocol::FEED) {
688                         return PageInfo::getFooterFromUrl($item['plink']);
689                 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED) && !$for_display) {
690                         $item['guid'] = '';
691                         $item['uri']  = '';
692                 }
693
694                 if ($add_media) {
695                         $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
696                 }
697
698                 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
699
700                 if (!empty($item['title'])) {
701                         $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
702                 }
703
704                 $shared = $this->getShareArray($item);
705
706                 // If it is a reshared post then reformat it to avoid display problems with two share elements
707                 if (!empty($shared)) {
708                         if (($item['network'] != Protocol::BLUESKY) && !empty($shared['guid']) && ($encapsulated_share = $this->createSharedPostByGuid($shared['guid'], true))) {
709                                 if (!empty(BBCode::fetchShareAttributes($item['body']))) {
710                                         $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encapsulated_share, $item['body']);
711                                 } else {
712                                         $item['body'] .= $encapsulated_share;
713                                 }
714                         }
715                         $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
716                 }
717
718                 $shared_content .= $item['body'] . '[/share]';
719
720                 return $shared_content;
721         }
722
723         /**
724          * Return the shared post from an item array (if the item is shared item)
725          *
726          * @param array $item
727          * @param array $fields
728          *
729          * @return array with the shared post
730          */
731         public function getSharedPost(array $item, array $fields = []): array
732         {
733                 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] != $item['uri-id'])) {
734                         $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
735                         if (is_array($shared)) {
736                                 return [
737                                         'comment' => BBCode::removeSharedData($item['body'] ?? ''),
738                                         'post'    => $shared
739                                 ];
740                         }
741                 }
742
743                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
744                 if (!empty($attributes)) {
745                         $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
746                         if (is_array($shared)) {
747                                 return [
748                                         'comment' => $attributes['comment'],
749                                         'post'    => $shared
750                                 ];
751                         }
752                 }
753
754                 return [];
755         }
756
757         /**
758          * Return share data from an item array (if the item is shared item)
759          * We are providing the complete Item array, because at some time in the future
760          * we hopefully will define these values not in the body anymore but in some item fields.
761          * This function is meant to replace all similar functions in the system.
762          *
763          * @param array $item
764          *
765          * @return array with share information
766          */
767         private function getShareArray(array $item): array
768         {
769                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
770                 if (!empty($attributes)) {
771                         return $attributes;
772                 }
773
774                 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] != $item['uri-id'])) {
775                         $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
776                         if (!empty($shared)) {
777                                 return [
778                                         'author'     => $shared['author-name'],
779                                         'profile'    => $shared['author-link'],
780                                         'avatar'     => $shared['author-avatar'],
781                                         'link'       => $shared['plink'],
782                                         'posted'     => $shared['created'],
783                                         'guid'       => $shared['guid'],
784                                         'message_id' => $shared['uri'],
785                                         'comment'    => $item['body'],
786                                         'shared'     => $shared['body'],
787                                 ];
788                         }
789                 }
790
791                 return [];
792         }
793
794         /**
795          * Add a link to a shared post at the end of the post
796          *
797          * @param string  $body
798          * @param integer $quote_uri_id
799          * @return string
800          */
801         public function addShareLink(string $body, int $quote_uri_id): string
802         {
803                 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
804                 if (empty($post)) {
805                         return $body;
806                 }
807
808                 $body = BBCode::removeSharedData($body);
809
810                 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);
811
812                 return $body;
813         }
814
815         public function storeAttachmentFromRequest(array $request): string
816         {
817                 $attachment_type  = $request['attachment_type'] ??  '';
818                 $attachment_title = $request['attachment_title'] ?? '';
819                 $attachment_text  = $request['attachment_text'] ??  '';
820
821                 $attachment_url     = hex2bin($request['attachment_url'] ??     '');
822                 $attachment_img_src = hex2bin($request['attachment_img_src'] ?? '');
823
824                 $attachment_img_width  = $request['attachment_img_width'] ??  0;
825                 $attachment_img_height = $request['attachment_img_height'] ?? 0;
826
827                 // Fetch the basic attachment data
828                 $attachment = ParseUrl::getSiteinfoCached($attachment_url);
829                 unset($attachment['keywords']);
830
831                 // Overwrite the basic data with possible changes from the frontend
832                 $attachment['type'] = $attachment_type;
833                 $attachment['title'] = $attachment_title;
834                 $attachment['text'] = $attachment_text;
835                 $attachment['url'] = $attachment_url;
836
837                 if (!empty($attachment_img_src)) {
838                         $attachment['images'] = [
839                                 0 => [
840                                         'src'    => $attachment_img_src,
841                                         'width'  => $attachment_img_width,
842                                         'height' => $attachment_img_height
843                                 ]
844                         ];
845                 } else {
846                         unset($attachment['images']);
847                 }
848
849                 return "\n" . PageInfo::getFooterFromData($attachment);
850         }
851
852         public function addCategories(array $post, string $category): array
853         {
854                 if (!empty($post['file'])) {
855                         // get the "fileas" tags for this post
856                         $filedas = FileTag::fileToArray($post['file']);
857                 }
858
859                 $list_array = explode(',', trim($category));
860                 $post['file'] = FileTag::arrayToFile($list_array, 'category');
861
862                 if (!empty($filedas) && is_array($filedas)) {
863                         // append the fileas stuff to the new categories list
864                         $post['file'] .= FileTag::arrayToFile($filedas);
865                 }
866                 return $post;
867         }
868
869         public function getACL(array $post, array $toplevel_item, array $request): array
870         {
871                 // If this is a comment, set the permissions from the parent.
872                 if ($toplevel_item) {
873                         $post['allow_cid'] = $toplevel_item['allow_cid'] ?? '';
874                         $post['allow_gid'] = $toplevel_item['allow_gid'] ?? '';
875                         $post['deny_cid']  = $toplevel_item['deny_cid'] ?? '';
876                         $post['deny_gid']  = $toplevel_item['deny_gid'] ?? '';
877                         $post['private']   = $toplevel_item['private'];
878                         return $post;
879                 }
880
881                 $user = User::getById($post['uid'], ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
882                 if (!$user) {
883                         throw new HTTPException\NotFoundException($this->l10n->t('Unable to fetch user.'));
884                 }
885
886                 $post['allow_cid'] = isset($request['contact_allow']) ? $this->aclFormatter->toString($request['contact_allow']) : $user['allow_cid'] ?? '';
887                 $post['allow_gid'] = isset($request['circle_allow'])  ? $this->aclFormatter->toString($request['circle_allow'])  : $user['allow_gid'] ?? '';
888                 $post['deny_cid']  = isset($request['contact_deny'])  ? $this->aclFormatter->toString($request['contact_deny'])  : $user['deny_cid']  ?? '';
889                 $post['deny_gid']  = isset($request['circle_deny'])   ? $this->aclFormatter->toString($request['circle_deny'])   : $user['deny_gid']  ?? '';
890
891                 $visibility = $request['visibility'] ?? '';
892                 if ($visibility === 'public') {
893                         // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected
894                         $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = '';
895                 } else if ($visibility === 'custom') {
896                         // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL
897                         // case that would make it public. So we always append the author's contact id to the allowed contacts.
898                         // See https://github.com/friendica/friendica/issues/9672
899                         $post['allow_cid'] .= $this->aclFormatter->toString(Contact::getPublicIdByUserId($post['uid']));
900                 }
901
902                 if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
903                         $post['private'] = ItemModel::PRIVATE;
904                 } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
905                         $post['private'] = ItemModel::UNLISTED;
906                 } else {
907                         $post['private'] = ItemModel::PUBLIC;
908                 }
909
910                 return $post;
911         }
912
913         public function moveAttachmentsFromBodyToAttach(array $post): array
914         {
915                 if (!preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/', $post['body'], $match)) {
916                         return $post;
917                 }
918
919                 foreach ($match[2] as $attachment_id) {
920                         $attachment = Attach::selectFirst(['id', 'uid', 'filename', 'filesize', 'filetype'], ['id' => $attachment_id, 'uid' => $post['uid']]);
921                         if (empty($attachment)) {
922                                 continue;
923                         }
924                         if ($post['attach']) {
925                                 $post['attach'] .= ',';
926                         }
927                         $post['attach'] .= Post\Media::getAttachElement(
928                                 $this->baseURL . '/attach/' . $attachment['id'],
929                                 $attachment['filesize'],
930                                 $attachment['filetype'],
931                                 $attachment['filename'] ?? ''
932                         );
933
934                         $fields = [
935                                 'allow_cid' => $post['allow_cid'], 'allow_gid' => $post['allow_gid'],
936                                 'deny_cid' => $post['deny_cid'], 'deny_gid' => $post['deny_gid']
937                         ];
938                         $condition = ['id' => $attachment_id];
939                         Attach::update($fields, $condition);
940                 }
941
942                 $post['body'] = str_replace($match[1], '', $post['body']);
943
944                 return $post;
945         }
946
947         private function setObjectType(array $post): array
948         {
949                 if (empty($post['post-type'])) {
950                         $post['post-type'] = empty($post['title']) ? ItemModel::PT_NOTE : ItemModel::PT_ARTICLE;
951                 }
952
953                 // embedded bookmark or attachment in post? set bookmark flag
954                 $data = BBCode::getAttachmentData($post['body']);
955                 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || !empty($data['type']))
956                         && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE)
957                 ) {
958                         $post['post-type'] = ItemModel::PT_PAGE;
959                         $post['object-type'] = Activity\ObjectType::BOOKMARK;
960                 }
961
962                 // Setting the object type if not defined before
963                 if (empty($post['object-type'])) {
964                         $post['object-type'] = ($post['gravity'] == ItemModel::GRAVITY_PARENT) ? Activity\ObjectType::NOTE : Activity\ObjectType::COMMENT;
965                 }
966                 return $post;
967         }
968
969         public function initializePost(array $post): array
970         {
971                 $post['network']    = Protocol::DFRN;
972                 $post['protocol']   = Conversation::PARCEL_DIRECT;
973                 $post['direction']  = Conversation::PUSH;
974                 $post['received']   = DateTimeFormat::utcNow();
975                 $post['origin']     = true;
976                 $post['wall']       = $post['wall'] ?? true;
977                 $post['guid']       = $post['guid'] ?? System::createUUID();
978                 $post['verb']       = $post['verb'] ?? Activity::POST;
979                 $post['uri']        = $post['uri'] ?? ItemModel::newURI($post['guid']);
980                 $post['thr-parent'] = $post['thr-parent'] ?? $post['uri'];
981
982                 if (empty($post['gravity'])) {
983                         $post['gravity'] = ($post['uri'] == $post['thr-parent']) ? ItemModel::GRAVITY_PARENT : ItemModel::GRAVITY_COMMENT;
984                 }
985
986                 $owner = User::getOwnerDataById($post['uid']);
987
988                 if (!isset($post['allow_cid']) || !isset($post['allow_gid']) || !isset($post['deny_cid']) || !isset($post['deny_gid'])) {
989                         $post['allow_cid'] = $owner['allow_cid'];
990                         $post['allow_gid'] = $owner['allow_gid'];
991                         $post['deny_cid']  = $owner['deny_cid'];
992                         $post['deny_gid']  = $owner['deny_gid'];
993                 }
994
995                 if (!isset($post['private'])) {
996                         if ($post['allow_gid'] || $post['allow_cid'] || $post['deny_gid'] || $post['deny_cid']) {
997                                 $post['private'] = ItemModel::PRIVATE;
998                         } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) {
999                                 $post['private'] = ItemModel::UNLISTED;
1000                         } else {
1001                                 $post['private'] = ItemModel::PUBLIC;
1002                         }
1003                 }
1004
1005                 if (empty($post['contact-id'])) {
1006                         $post['contact-id'] = $owner['id'];
1007                 }
1008
1009                 if (empty($post['author-link']) && empty($post['author-id'])) {
1010                         $post['author-link']   = $owner['url'];
1011                         $post['author-id']     = Contact::getIdForURL($post['author-link']);
1012                         $post['author-name']   = $owner['name'];
1013                         $post['author-avatar'] = $owner['thumb'];
1014                 }
1015
1016                 if (empty($post['owner-link']) && empty($post['owner-id'])) {
1017                         $post['owner-link']   = $post['author-link'];
1018                         $post['owner-id']     = Contact::getIdForURL($post['owner-link']);
1019                         $post['owner-name']   = $post['author-name'];
1020                         $post['owner-avatar'] = $post['author-avatar'];
1021                 }
1022
1023                 return $post;
1024         }
1025
1026         public function finalizePost(array $post): array
1027         {
1028                 if (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $post['body'], $matches)) {
1029                         $post['body'] = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $post['body']);
1030                 }
1031
1032                 // Convert links with empty descriptions to links without an explicit description
1033                 $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body']));
1034                 $post['body'] = $this->bbCodeVideo->transform($post['body']);
1035                 $post = $this->setObjectType($post);
1036
1037                 // Personal notes must never be altered to a group post.
1038                 if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) {
1039                         // Look for any tags and linkify them
1040                         $post = $this->expandTags($post);
1041                 }
1042
1043                 return $post;
1044         }
1045
1046         public function postProcessPost(array $post, array $recipients = [])
1047         {
1048                 if (!\Friendica\Content\Feature::isEnabled($post['uid'], 'explicit_mentions') && ($post['gravity'] == ItemModel::GRAVITY_COMMENT)) {
1049                         Tag::createImplicitMentions($post['uri-id'], $post['thr-parent-id']);
1050                 }
1051
1052                 Hook::callAll('post_local_end', $post);
1053
1054                 $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $post['uid'], 'self' => true]);
1055
1056                 foreach ($recipients as $recipient) {
1057                         $address = trim($recipient);
1058                         if (!$address) {
1059                                 continue;
1060                         }
1061
1062                         $this->emailer->send(new ItemCCEMail(
1063                                 $this->app,
1064                                 $this->l10n,
1065                                 $this->baseURL,
1066                                 $post,
1067                                 $address,
1068                                 $author['thumb'] ?? ''
1069                         ));
1070                 }
1071         }
1072
1073         public function copyPermissions(int $fromUriId, int $toUriId)
1074         {
1075                 $from        = Post::selectFirstPost(['author-id'], ['uri-id' => $fromUriId]);
1076                 $from_author = DBA::selectFirst('account-view', ['ap-followers'], ['id' => $from['author-id']]);
1077                 $to          = Post::selectFirstPost(['author-id'], ['uri-id' => $toUriId]);
1078                 $to_author   = DBA::selectFirst('account-view', ['ap-followers'], ['id' => $to['author-id']]);
1079
1080                 $existing = array_column(Tag::getByURIId($toUriId, [Tag::TO, Tag::CC, Tag::BCC]), 'url');
1081
1082                 foreach (Tag::getByURIId($fromUriId, [Tag::TO, Tag::CC, Tag::BCC]) as $receiver) {
1083                         if ($receiver['url'] == $from_author['ap-followers']) {
1084                                 $receiver['url']  = $to_author['ap-followers'];
1085                                 $receiver['name'] = trim(parse_url($receiver['url'], PHP_URL_PATH), '/');
1086                         }
1087                         if (in_array($receiver['url'], $existing)) {
1088                                 continue;
1089                         }
1090                         Tag::store($toUriId, $receiver['type'], $receiver['name'], $receiver['url']);
1091                 }
1092         }
1093 }