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